JS [ES5] 如何用 setter 和 getter 分配对象?

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

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

使用 use strict 会出错.

我想组合多个对象:使用 jQuery.extend():

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

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

使用 ES6 Object.assign:

with ES6 Object.assign:

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

在任何情况下,getter 都会变成常规属性,因此可以更改.如何避免?

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;
}

但请注意,Object.assign 不这样做是有充分理由的,如果 getter 和 setter 是闭包,它可能会产生奇怪的效果.

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

相关文章