Object.defeProperty()在 JavaScript 中的奇怪行为

我在下面玩 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
4261 次浏览

您应该将 enumerable设置为 true。在 Object.defineProperty中默认设置为 false。根据 MDN

数不胜数

当且仅当此属性在枚举对应对象的属性期间显示时,才显示 true。 < br > < br > 默认为 false。

不可枚举意味着属性不会在 Object.keys()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对象上的所有属性和方法都是不可枚举的。这就是为什么您可以从实例中调用它们,但是它们在迭代时不会出现的原因。

要获取所有属性(包括不可枚举的) < a href = “ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global _ Objects/Object/getOwnPropertyNames”rel = “ norefrer”> 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

默认情况下,使用 defineProperty定义的属性不是 数不胜数-这意味着在迭代它们的 Object.keys时它们不会显示(这是代码片段控制台所做的)。(类似地,数组的 length属性不会显示,因为它是不可枚举的。)

MDN:

数不胜数

当且仅当此属性在枚举相应对象的属性时显示时为 true。

默认为 false。

让它具有可枚举性:

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

你可以在 日志图像中看到这个属性的原因是 Chrome 的控制台也会显示不可枚举的属性 -但是不可枚举的属性会稍微变成灰色:

enter image description here

看看如何 age是灰色的,而 name不是-这表明 name是可枚举的,而 age不是。

无论何时使用”。对象的方法。您应该更好地定义描述符的所有属性。因为如果你没有定义其他属性描述符,那么它会假设所有属性的默认值都是 false。因此,您的 console.log 检查所有可枚举的: true 属性并记录它们。

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