Strange behavior of Object.defineProperty() in JavaScript

后端 未结 3 1299
梦如初夏
梦如初夏 2020-12-08 18:05

I was playing with below javascript code. Understanding of Object.defineProperty() and I am facing a strange issue with it. When I try to execute below code in

3条回答
  •  心在旅途
    2020-12-08 18:45

    Whenever you use".defineProperty" method of object. You should better define all the properties of the descriptor. Because if you don't define other property descriptor then it assumes default values for all of them which is false. So your console.log checks for all the enumerable : true properties and logs them.

    //Code Snippet 
    let profile = {
      name: 'Barry Allen',
    }
    
    // I added a new property in the profile object.
    Object.defineProperty(profile, 'age', {
      value: 23,
      writable: true,
      enumerable : true,
      configurable : true
    })
    
    console.log(profile)
    console.log(profile.age)
    

提交回复
热议问题