簡體   English   中英

為什么console.log()不顯示Object.create的繼承屬性?

[英]Why does console.log() not show inherited properties from Object.create?

我試圖在基礎對象上利用Object.defineProperty()時遇到掛起。 我想使用Object.create()繼承該對象的屬性,然后在派生對象中定義更多屬性(可以從那里繼承)。 我應該注意到我的目標是node.js.

這是一個例子:

var Base = {};

Object.defineProperty(Base, 'prop1', {
    enumerable:true,
    get:function(){ return 'prop1 value';}
});

Object.defineProperty(Base, 'prop2', {
    enumerable:true,
    value : 'prop 2 value'
});

Object.defineProperty(Base, 'create', {
    value:function(){
        return Object.create(Base);
    }
});

console.log(Base);

var derived = Base.create();

Object.defineProperty(derived, 'prop3', {
    enumerable:true,
    value:'prop 3 value'
});

console.log(derived);

其中輸出如下:

{ prop1: [Getter], prop2: 'prop 2 value' }
{ prop3: 'prop 3 value' }

我認為console.log()會枚舉繼承的屬性,以及我在派生對象上定義的屬性prop3 它似乎沒有查找以這種方式定義的屬性的原型層次結構。 那是對的嗎?

我查看了覆蓋我的對象的toString()方法,但似乎console.log()沒有調用它。

  1. 如何記錄所有屬性而不必枚舉它們?
  2. 這是實現繼承的有效方法嗎?

編輯:

  1. node.js的庫中是否有另一個函數可以完成這項工作並記錄繼承的屬性?

你可以在可用的地方使用console.dir()

console.dir(derived) 

它將在__proto__對象上顯示對象的繼承屬性

編輯:雖然似乎沒有顯示在節點上

Firebug 記錄繼承的屬性:

在此輸入圖像描述

而Chrome為您提供了一個包含繼承屬性的樹視圖:

在此輸入圖像描述

暫無
暫無

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

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