我很困惑为什么我不能从构造函数的对象实例中删除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, {
f: {
get: function(){
return 100
},
configurable: true
}
});
//tried to delete but got response as false.
console.log(delete o.f);
console.log(o.f);