Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any effective difference between the get operator and defineProperty?

Tags:

javascript

Is there any real difference between the get operator:

var obj = {
    get prop () {
        //insert code here
    }
};

and using defineProperty:

var obj;
Object.defineProperty(obj, "prop", {
    get: function () {
        //insert code here
    }
}

The MDN pages say that compatibility is about the same.

like image 897
Hello71 Avatar asked Oct 09 '11 03:10

Hello71


1 Answers

Object.defineProperty will default to enumerable: false and configurable: false, while the object literal getter syntax will default to enumerable: true and configurable: true. This can be verified with Object.getOwnPropertyDescriptor(obj, "prop").

This means that in the former case prop will show up in for-in loops and Object.keys(obj), and doing a delete obj.prop will fail (noisily in strict mode, silently otherwise). The opposite will be true for the latter case.

Note that Object.defineProperty (or Object.create or Object.defineProperties) will allow you to separately choose the configurability and enumerability of your properties, while the object literal getter syntax will not.

like image 118
Domenic Avatar answered Nov 01 '22 16:11

Domenic