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

Is there any real difference between the get statement:

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

and using defineProperty :

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

MDN pages say compatibility is about the same.

+6
source share
1 answer

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

This means that in the first case, prop will be displayed in for - in and Object.keys(obj) , and the delete obj.prop will fail (noisy in strict mode, silently otherwise). In the latter case, the opposite will be the case.

Note that Object.defineProperty (or Object.create or Object.defineProperties ) will allow you to individually select the configuration and enumeration of your properties, while the getter syntax of the object will not.

+8
source

Source: https://habr.com/ru/post/898911/


All Articles