💾.assignDescriptors()

JSobjectsextending objectsmixin ⟩ 💾 Object.assignDescriptors()

☢️ Alert:

Don't use Object.assign() with sources that have getters, the inner states of the sources may change❗❗❗

/*****************************************************************
 *                 Object.assignDescriptors()                    *
 *****************************************************************
 *
 * • copies property descriptors from sources into the target
 *   instead of just copying property values. 
 * 
 * • copies all own properties (both enumerable and non-enumerable).
 * • copies getters from sources and overwrites setters in the target
 *   rather than invoking those getters/setters.
 *
 * • propagates any TypeErrors thrown by `Object.defineProperty()`:
 *   • if the target is sealed or frozen or 
 *   • if any of the source properties try to change an existing
 *     non-configurable property on the target.
 */
Object.defineProperty(Object, "assignDescriptors", {
    
    // match the attributes of `Object.assign()`
    writable    : true,
    enumerable  : false,
    configurable: true,

    // value of the `assignDescriptors` property.
    value: function(target, ...sources) {
        
        for(let source of sources) { 
        
            // copy properties with string key
            for(let name of Object.getOwnPropertyNames(source)) { 
                let desc = Object.getOwnPropertyDescriptor(source, name);
                Object.defineProperty(target, name, desc); 
            }
            
            // copy propertyes with symbol key
            for(let symbol of Object.getOwnPropertySymbols(source)) { 
                let desc = Object.getOwnPropertyDescriptor(source, symbol); 
                Object.defineProperty(target, symbol, desc); 
            }
            
        }
        
        return target;
    } 
});

Last updated