when do you use Object.defineProperty()

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

    Features like 'enumerable' are rarely used in my experience. The major use case is computed properties:

    var myObj = {};
    
    myObj.width = 20;
    myObj.height = 20;
    
    Object.defineProperty(myObj, 'area', {
        get: function() {
            return this.width*this.height;
        }
    });
    console.log(myObj.area);
    

提交回复
热议问题