开发者

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

开发者 https://www.devze.com 2023-04-12 05:35 出处:网络
Is there any real difference between the get operator: var obj = { get prop () { //insert code here } }; and using defineProperty:

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: 开发者_Go百科function () {
        //insert code here
    }
}

The MDN pages say that compatibility is about the same.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消