为什么console.log()不显示Object.create的继承属性? [英] Why does console.log() not show inherited properties from Object.create?
问题描述
我试图在基础对象上利用 Object.defineProperty()
时遇到挂起。我想使用 Object.create()
继承该对象的属性,然后在派生对象中定义更多属性(可以从那里继承)。我应该注意到我的目标是在node.js。
I am running into a hangup while trying to leverage Object.defineProperty()
on a base object. I want to inherit properties from that object, using Object.create()
, and then define more properties in the derived object (which may be inherited from there). I should note that I am targetting this at 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
我是在派生对象上定义。看起来它不会查找以这种方式定义的属性的原型层次结构。这是正确的吗?
I thought that console.log() would enumerate the inherited properties, as well as the property prop3
that I defined on the derived object. It would seem that it does not look up the prototype hierarchy for properties defined in this way. Is that correct?
我看着覆盖我的对象的 toString()
方法,但似乎是控制台.log()不会调用它。
I looked at overriding the toString()
method for my object, but it seems that console.log() does not call that.
- 如何记录所有属性而不必枚举它们?
- 这是实现继承的有效方式吗?
编辑:
- node.js库中是否有另一个函数可以完成这项工作并记录继承的属性?
推荐答案
Firebug 记录继承的属性:
Firebug does log the inherited properties:
而Chrome为您提供了一个树视图,其中包括继承的属性:
while Chrome gives you a tree-view which includes the inherited properties:
这篇关于为什么console.log()不显示Object.create的继承属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!