when do you use Object.defineProperty()

前端 未结 10 2346
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 01:31

I\'m wondering when I should use

Object.defineProperty

to create new properties for an object. I\'m aware that I\'m able to set things lik

10条回答
  •  伪装坚强ぢ
    2020-12-08 02:23

    Object.defineProperty is mainly used to set properties with specific property descriptors (e.g. read-only (constants), enumerability (to not show a property in a for (.. in ..) loop, getters, setters).

    "use strict";
    var myObj = {}; // Create object
    // Set property (+descriptor)
    Object.defineProperty(myObj, 'myprop', {
        value: 5,
        writable: false
    });
    console.log(myObj.myprop);// 5
    myObj.myprop = 1;         // In strict mode: TypeError: myObj.myprop is read-only
    

    Example

    This method extends the Object prototype with a property. Only the getter is defined, and the enumerability is set to false.

    Object.defineProperty(Object.prototype, '__CLASS__', {
        get: function() {
            return Object.prototype.toString.call(this);
        },
        enumerable: false // = Default
    });
    Object.keys({});           // []
    console.log([].__CLASS__); // "[object Array]"
    

提交回复
热议问题