Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - Why does console.log() not show inherited properties from Object.create?

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.

Here's an example:

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);

Which outputs the following:

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

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?

I looked at overriding the toString() method for my object, but it seems that console.log() does not call that.

  1. How can I get all properties logged without having to enumerate through them?
  2. Is this a valid way to implement inheritance?

EDIT:

  1. Is there another function in node.js' libraries that would do the job and log the inherited properties?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use console.dir() where available

console.dir(derived) 

and it'll show the inherited properties of your object on the __proto__ object

Edit : doesnt seem to show up on node though


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...