如何解决为什么我无法从对象实例中删除 getter 函数?
我很困惑为什么我无法从构造函数的对象实例中删除 getter 函数:
//created constructor function
let f = function () {
this.a = 1;
this.b = 2;
}
//created an instance
let o = new f()
//created a getter function on object o
Object.defineProperties(o,{f:
{get: function(){
return 100
}
}})
//tried to delete but got response as false.
delete o.f
解决方法
您只能删除可配置属性。来自 MDN:
configurable
true
如果该属性描述符的类型可以改变,并且该属性可以从相应的对象中删除。默认为 false
。
//created constructor function
let f = function () {
this.a = 1;
this.b = 2;
}
//created an instance
let o = new f()
//created a getter function on object o
Object.defineProperties(o,{
f: {
get: function(){
return 100
},configurable: true,}
})
console.log(delete o.f);
那是因为您没有将 f
属性设置为 configurable
:
//created constructor function
let f = function () {
this.a = 1;
this.b = 2;
}
//created an instance
let o = new f()
//created a getter function on object o
Object.defineProperties(o,configurable: true
}
});
//tried to delete but got response as false.
console.log(delete o.f);
console.log(o.f);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。