简体   繁体   English

在 JavaScript 中使用“defineProperty”后重置对象属性 getter/setter

[英]Reset object property getter/setter after using "defineProperty" in JavaScript

I want to "reset" the getter/setter after I changed them using "defineProperty".我想在使用“defineProperty”更改它们后“重置”getter/setter。

The output of the example should be 1 -> nope -> 1, but I just get "undefined".该示例的输出应该是 1 -> nope -> 1,但我只是得到“未定义”。

How can I clear the custom getter, so I it will go with the native default getter?如何清除自定义 getter,以便它与本机默认 getter 一起使用?

 var obj = { a: '1', b: '2' }; console.log(obj.a); Object.defineProperty(obj, 'a', { get: function(){ return 'nope'; }, configurable: true }); console.log(obj.a); Object.defineProperty(obj, 'a', { get: undefined, configurable: true }); console.log(obj.a);

I don't see how you'd ever get back to your defaults without cloning obj - because that first getter in essence destroys the original value of 'a';我不知道如果不克隆 obj,您将如何恢复默认值 - 因为第一个 getter 本质上会破坏 'a' 的原始值; it's the same as saying obj.a = 'nope' .这与说obj.a = 'nope'相同。

Something like this will work:像这样的事情会起作用:

let obj = {
    a: '1',
  b: '2'
};
const objOrig = JSON.parse(JSON.stringify(obj))

console.log(obj.a);

Object.defineProperty(obj, 'a', {
  get: function(){ return 'nope'; },
  configurable: true
});

console.log(obj.a);

obj = JSON.parse(JSON.stringify(objOrig))

console.log(obj.a);

And note if you ever need to delete a getter you can;并注意,如果您需要删除一个 getter,您可以;

delete obj.a

but it won't revert to the original declaration;但它不会恢复到原始声明; 'a' is lost at this point. 'a' 在这一点上丢失了。

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

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