when do you use Object.defineProperty()

前端 未结 10 2347
爱一瞬间的悲伤
爱一瞬间的悲伤 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:31

    A really good reason for using Object.defineProperty is that it lets you loop through a function in an object as a computed property, which executes the function instead of returning the function's body.

    For example:

    var myObj = {};
    
    myObj.width = 20;
    myObj.height = 20;
    
    Object.defineProperty(myObj, 'area', {
        get: function() {
            return this.width*this.height;
        },
        enumerable: true
    });
    
    for (var key in myObj) {
      if (myObj.hasOwnProperty(key)) {
        console.log(key + " -> " + myObj[key]);
      }
    }
    //width -> 20, height -> 20, area -> 400
    

    Versus adding the function as a property to an object literal:

    var myObj = {};
    
    myObj.width = 20;
    myObj.height = 20;
    
    myObj.area = function() {
           return this.width*this.height;
        };
    
    for (var key in myObj) {
      if (myObj.hasOwnProperty(key)) {
        console.log(key + " -> " + myObj[key]);
      }
    }
    // width -> 20, height -> 20, area -> function() { return this.width*this.height;}
    

    Make sure you set the enumerable property to true in order to loop through it.

提交回复
热议问题