簡體   English   中英

JavaScript:無法打印由Object.defineProperty定義的對象屬性

[英]Javascript: Can't print object property defined by Object.defineProperty

我使用Object.defineProperty方法來定義對象的屬性:

const o = { a: 1 }
Object.defineProperty(o, 'b', {
  get() {
    return this.a
  }, set(value) {
    this.a = value
  }
})

但是,當我使用console.log嘗試打印對象ob屬性似乎不在其中。

但是,當我嘗試使用ob進行訪問時,它可以返回正確的值

所以我很困惑:為什么該屬性無法打印但可以訪問?

默認情況下,用.defineProperty()添加的屬性是不可枚舉的

通過設置enumerable: true使它們“可見” enumerable: true

 var foo = {} Object.defineProperty(foo, "a", { get() { return "a"; } }); Object.defineProperty(foo, "b", { get() { return "b"; }, enumerable: true }); console.log(Object.keys(foo)); 

好吧,您擁有自己的可枚舉屬性和對象的所有自己的屬性。

要獲取所有可枚舉的自身屬性,可以采用Object.keys ;對於非不可枚舉的屬性,也可以采用Object.getOwnPropertyNames

也許console.log僅顯示對象的可枚舉屬性。 此實現取決於供應商。

 const o = { a: 1 } Object.defineProperty(o, 'b', { get() { return this.a }, set(value) { this.a = value } }) console.log(o); console.log(Object.keys(o)); console.log(Object.getOwnPropertyNames(o)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以使用Object.getOwnPropertyNames獲得propertyNames

 const o = { a: 1 } Object.defineProperty(o, 'b', { get() { return this.a }, set(value) { this.a = value } }) console.log(Object.getOwnPropertyNames(o)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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