簡體   English   中英

"JavaScript 中 Object.defineProperty() 的奇怪行為"

[英]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 

默認情況下,您使用defineProperty<\/code>定義的屬性是不可枚舉<\/em>的——這意味着當您遍歷它們的Object.keys<\/code> (這是代碼段控制台所做的)時,它們不會顯示。 (同樣,數組的length<\/code>屬性也不會顯示,因為它是不可枚舉的。)

MDN<\/a> :

可枚舉的<\/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM