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

我怕爱的太早我们不能终老 提交于 2019-12-01 06:14:47

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/25141170/how-do-chrome-and-firefox-print-the-objects-class-name-in-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!