JavaScript 中 Object.defineProperty() 的奇怪行为

2024-01-09

我正在玩下面的 JavaScript 代码。对此事的认知Object.defineProperty()我面临着一个奇怪的问题。当我尝试在浏览器或 VS 代码中执行以下代码时,输​​出不符合预期,而如果我尝试调试代码,输出是正确的

当我调试代码并评估配置文件时,我可以看到name & age对象中的属性 但在输出时,它只显示name财产

//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)

现在这里的预期输出应该是

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

但我得到的输出为。 请注意,我能够访问age之后定义的属性。 我不知道为什么console.log()就是这样的行为。

{name: "Barry Allen"}
23 

你应该设置enumerable to true. In Object.defineProperty its false默认情况下。根据MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description.

可枚举的

true当且仅当该属性在相应对象的属性枚举期间出现。

默认为 false。

不可枚举意味着属性不会显示在Object.keys() or for..in控制台中都不循环

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)

上的所有属性和方法prototype内置类的对象是不可枚举的。这就是您可以从实例调用它们但它们在迭代时不会出现的原因。

获取所有属性(包括不可枚举的)Object​.get​OwnProperty​Names() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames.

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中 Object.defineProperty() 的奇怪行为 的相关文章

随机推荐