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

前端 未结 1 788
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 13:27
obj1 = Object.create({}, { property: { enumerable: true, value: 42 } })

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

with use st

相关标签:
1条回答
  • 2021-01-21 14:25

    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.

    0 讨论(0)
提交回复
热议问题