简体   繁体   中英

Strange behavior of Object.defineProperty() in JavaScript

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 the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct

When I debug the code and evaluate the profile I can see the name & age property in the object But at the time of output, it only shows the name property

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

Now expected output here should be

{name: "Barry Allen", age: 23}
23

but I get the output as. Note that I am able to access the age property defined afterwards. I am not sure why the console.log() is behaving this way.

{name: "Barry Allen"}
23 

You should set enumerable<\/code> to true<\/code> . In Object.defineProperty<\/code> its false<\/code> by default. According to MDN<\/a> .



true<\/code> if and only if this property shows up during enumeration of the properties on the corresponding object.

Defaults to false.<\/strong>

Thats is the reason you can call them from instance but they don't appear while iterating.

By default, properties you define with defineProperty<\/code> are not enumerable<\/em> - this means that they will not show up when you iterate over their Object.keys<\/code> (which is what the snippet console does). (Similarly, the length<\/code> property of an array does not get displayed, because it's non-enumerable.)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM