Strange behavior of Object.defineProperty() in JavaScript

后端 未结 3 1296
梦如初夏
梦如初夏 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:47

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

    See MDN:

    enumerable

    true if and only if this property shows up during enumeration of the properties on the corresponding object.

    Defaults to false.

    Make it enumerable instead:

    //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
    })
    
    console.log(profile)
    console.log(profile.age)

    The reason you can see the property in the logged image is that Chrome's console will show you non-enumerable properties as well - but the non-enumerable properties will be slightly greyed-out:

    See how age is grey-ish, while name is not - this indicates that name is enumerable, and age is not.

提交回复
热议问题