简体   繁体   English

Chrome和Firefox如何在控制台中打印对象的类名?

[英]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: 如果我使用“传统”Javascript类创建Foo类,则在控制台上打印Foo实例时,chrome和Firefox都会显示Foo名称:

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. 到目前为止,我能想到的唯一方法是一个丑陋的黑客滥用eval为mkClass返回的当前匿名构造函数赋予不同的名称。

It seems that FF and chrome just print constructor property . 似乎FF和chrome只是打印构造函数属性 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Chrome或Firefox的JavaScript控制台中引用最后的打印输出对象? - How to refer to the last print out Object in JavaScript console of Chrome or Firefox? 如何获得像 Chrome 的开发控制台一样的“类”名称? - How to get 'class' name like Chrome's dev console? 为什么 Chrome 和 FireFox 控制台打印“未定义”? - Why does Chrome & FireFox console print 'undefined'? 如何让chrome的控制台显示具有动态更改名称的功能? - How do I get chrome's console to display a function with its dynamically changed name? 在控制台上打印链接的名称 - Print on the console the link's name 如何在 Google Chrome JavaScript 控制台中打印调试消息? - How do I print debug messages in the Google Chrome JavaScript Console? 有没有更简单的方法来从firefox或chrome的开发人员控制台查看json对象? - Is there an easier way to view json object from firefox or chrome's developer console? 如何在Chrome,Firebug和Firefox的控制台中显示数组的所有条目? - How to display all entries of an array within Chrome's, Firebug's and Firefox's console? 如何在Firefox / Chrome控制台中显示文档字符串? - How to show documentation string in Firefox / Chrome console? 如何在Electron js中将消息打印到openDevTools的控制台? - How do you print messages to openDevTools's console in Electron js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM