[英]Strange behavior of Object.defineProperty() in 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
您應該將
enumerable<\/code>設置為
true<\/code> 。
在
Object.defineProperty<\/code>中默認為
false<\/code> 。
根據MDN<\/a> 。
可枚舉的<\/strong>
當且僅當在枚舉相應對象的屬性期間顯示此屬性時才為
true<\/code> 。
默認為假。<\/strong>
不可枚舉意味着屬性不會在
Object.keys()<\/code>或
for..in<\/code>循環中顯示,也不會在控制台中顯示
內置類的
prototype<\/code>對象上的所有屬性和方法都是不可枚舉的。
這就是您可以從實例調用它們但它們在迭代時不會出現的原因。
獲取所有屬性(包括不可枚舉的)
Object.getOwnPropertyNames()<\/code><\/a> 。
默認情況下,您使用
defineProperty<\/code>定義的屬性是不可枚舉<\/em>的——這意味着當您遍歷它們的
Object.keys<\/code> (這是代碼段控制台所做的)時,它們不會顯示。
(同樣,數組的
length<\/code>屬性也不會顯示,因為它是不可枚舉的。)
可枚舉的<\/strong>
當且僅當在枚舉相應對象的屬性期間顯示此屬性時才為 true。
默認為假。<\/strong>
您可以在記錄的圖像<\/a>中看到該屬性的原因是 Chrome 的控制台也會向您顯示不可枚舉的屬性 -但不可枚舉的屬性將略微變灰<\/strong>:
看看
age<\/code>是灰色的,而
name<\/code>不是 - 這表明
name<\/code>是可枚舉的,而
age<\/code>不是。
每當您使用對象的“.defineProperty”方法時。 您應該更好地定義描述符的所有屬性。 因為如果您不定義其他屬性描述符,那么它會假定所有這些屬性的默認值都是錯誤的。 因此,您的 console.log 會檢查所有 enumerable : 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.