Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How do Chrome and Firefox print the object's class name in the console?

If I create a Foo class using "traditional" Javascript classes, both chrome and Firefox will show the Foo name when printing Foo instances on the console:

function Foo(){
    this.x = 10;
}

console.log(new Foo());
// Foo {x: 10}

On the other hand, if I use hand rolled prototypal inheritance then I don't get the helpful name when debugging

function mkClass(init, proto){
    return function(/**/){
         var obj = Object.create(proto);
         init.apply(obj, arguments);
         return obj;
    }
}

var Bar = mkClass(function(){ this.x = 10 }, {});

console.log(Bar());
// Object {x: 10}

Is there a way to have classes created via my prototypal system show their name when printed on the console? So far, the only way I could think of is an ugly hack abusing eval to give different names to the currently anonymous constructor function that mkClass returns.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It seems that FF and chrome just print constructor property. Try setting it to something meaningful and you should see the result.

function mkClass(init, proto){
    proto.constructor = {name: "Foo"};
    return function(/**/){
         var obj = Object.create(proto);
         init.apply(obj, arguments);
         return obj;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...