JS [ES5] How to assign objects with setters and getters?

obj1 = Object.create({}, { property: { enumerable: true, value: 42 } })

> obj1.property = 56
> 56
> obj1.property
> 42

with use strict there is an error.

I want to combine multiple objects: with jQuery.extend():

new_obj = $.extend(true, objN, obj1)

with ES6 Object.assign:

new_obj = Object.assign({}, objN, obj1)

In any case, the getter turns into a regular property, and therefore it can be changed. How to avoid it?



You can write your own function that also copies over property attributes:

function extend(target, ...sources) {
    for (let source of sources)
        for (let key of Object.keys(source))
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    return target;

But notice there is good reason why Object.assign does not, it could have weird effects if getters and setters are closures.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.