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

浪尽此生 提交于 2019-12-20 03:29:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37054596/js-es5-how-to-assign-objects-with-setters-and-getters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!