when do you use Object.defineProperty()

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

    @Gerard Simpson

    If 'area' should be enumerable it can be written without Object.defineProperty, too.

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

提交回复
热议问题