Chrome和Firefox如何在控制台中打印对象的类名? [英] How do Chrome and Firefox print the object's class name in the console?
问题描述
如果我使用传统" Javascript类创建Foo类,则在控制台上打印Foo实例时,chrome和Firefox都将显示Foo名称:
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}
有没有办法让通过我的原型系统创建的类在控制台上打印时显示其名称?到目前为止,我能想到的唯一方法是丑陋的黑客滥用评估以赋予其不同的声誉. mkClass返回的当前匿名构造函数的名称.
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.
推荐答案
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;
}
}
这篇关于Chrome和Firefox如何在控制台中打印对象的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!