when do you use Object.defineProperty()

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

    Object.defineProperty prevents you from accidentally assigning values to some key in its prototype chain. With this method you assign only to that particular object level(not to any key in prototype chain).

    For example: There is an object like {key1: value1, key2: value2} and you don't know exactly its prototype chain or by mistake you miss it and there is some property 'color' somewhere in prototype chain then-

    using dot(.) assignment-

    this operation will assign value to key 'color' in prototype chain(if key exist somewhere) and you will find the object with no change as . obj.color= 'blue'; // obj remain same as {key1: value1, key2: value2}

    using Object.defineProperty method-

    Object.defineProperty(obj, 'color', {
      value: 'blue'
    });
    

    // now obj looks like {key1: value1, key2: value2, color: 'blue'}. it adds property to the same level.Then you can iterate safely with method Object.hasOwnProperty().

提交回复
热议问题