简体   繁体   English

如何从JavaScript对象中删除setter?

[英]How to remove the setter from a JavaScript object?

Consider the following code: 请考虑以下代码:

var x = 0;

var o = {};

function getter() {
    return x;
}

Object.defineProperty(o, "y", {
    get: getter,
    set: function (y) {
        x = y;

        Object.defineProperty(o, "y", {
            get: getter
        });
    },
    configurable: true
});

My objective is to remove the setter and make the property oy non-configurable after the setter has been called once. 我的目标是消除setter和使财产oy不可配置的setter被调用一次之后。 However it doesn't work as expected: 但是它没有按预期工作:

> x       // 0
> o.y     // 0
> o.y = 1 // 1
> x       // 1
> o.y     // 1
> o.y = 2 // 2
> x       // 2
> o.y     // 2

So my code did not work as expected, and I can't think of any other solution. 所以我的代码没有按预期工作,我想不出任何其他解决方案。 Hence this question. 因此这个问题。

Think of the redefine operation like this: each key in the new definition replaces the corresponding key in the old definition. 可以考虑重新定义这样的操作:新定义中的每个键都替换旧定义中的相应键。 Since you do not specify a set key when you redefine the property, it retains its old value. 由于在重新定义属性时未指定set键,因此它将保留其旧值。

You need to explicitly include it as undefined in order to get rid of it, and in fact you don't need to set the getter at all because you are not changing it: 你需要明确地将它包含为undefined以便摆脱它,事实上你根本不需要设置getter,因为你没有改变它:

Object.defineProperty(o, "y", {
    set: undefined
});

Then, in my tests: 然后,在我的测试中:

o.y     // 0
o.y = 1
o.y     // 1
o.y = 2
o.y     // 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM