简体   繁体   中英

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

I am confused as to why I am unable to delete a getter function from an object instance of a constructor function:

//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

You can only delete configurable properties. From 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 of);

That's because you didn't set the f property as 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 of); console.log(of);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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