Strange behavior of Object.defineProperty() in JavaScript

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

    You should set enumerable to true. In Object.defineProperty its false by default. According to MDN.

    enumerable

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

    Defaults to false.

    Non-enumerable means that property will not be shown in Object.keys() or for..in loop neither in console

    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)

    All the properties and methods on prototype object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.

    To get all properties(including non-enumerable)Object​.get​OwnProperty​Names() .

    let profile = {
        name: 'Barry Allen',
    }
    
    // I added a new property in the profile object.
    
    Object.defineProperty(profile , 'age', {
        value: 23,
        writable: true,
        enumerable: false
    })
    for(let key in profile) console.log(key) //only name will be displayed.
    
    console.log(Object.getOwnPropertyNames(profile)) //You will se age too

提交回复
热议问题