JS [ES5]如何使用setter和getter分配对象? [英] JS [ES5] How to assign objects with setters and getters?

查看:259
本文介绍了JS [ES5]如何使用setter和getter分配对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用使用严格时出现错误。

我想要组合多个对象:
with jQuery.extend():

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)

在任何情况下,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 不会,如果getters和setter都是闭包,它可能会有奇怪的效果。

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

这篇关于JS [ES5]如何使用setter和getter分配对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆