JavaScript中Object.defineProperty()的奇怪行为 [英] Strange behavior of Object.defineProperty() in JavaScript
问题描述
我正在使用下面的JavaScript代码.了解Object.defineProperty()
之后,我面临着一个奇怪的问题.当我尝试在浏览器或VS代码中执行以下代码时,输出结果与预期不符,而如果我尝试调试代码,则输出结果正确
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
当我调试代码并评估配置文件时,我可以在对象中看到name & age
属性
但是在输出时,它仅显示name
属性
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
但是我得到的输出是.
请注意,我能够访问之后定义的age
属性.
我不知道为什么console.log()
会采用这种方式.
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
推荐答案
您应将enumerable
设置为true
.在Object.defineProperty
中,默认情况下为false
.根据 MDN .
You should set enumerable
to true
. In Object.defineProperty
its false
by default. According to MDN.
可枚举
true
当且仅当在枚举相应对象的属性时显示此属性.
默认为false.
enumerable
true
if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Non-enumerable意味着该属性将不会在控制台的Object.keys()
或for..in
循环中显示
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)
内置类的prototype
对象上的所有属性和方法都是不可枚举的.这就是您可以从实例中调用它们的原因,但是它们在迭代时不会出现.
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.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
这篇关于JavaScript中Object.defineProperty()的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!