为什么我无法从对象实例中删除 getter 函数?

Why am I unable to delete a getter function from an object instance?

我很困惑为什么我无法从构造函数的对象实例中删除 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 if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to 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);