js如何将objectName打印到控制台 [英] js how to print the objectName to console
本文介绍了js如何将objectName打印到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用webdev工具控制台时,如果键入浏览器对象,则返回控制台
When using the webdev tools console, if type a browser object, it returns console
> console
Console { }
> console+""
"[object Console]"
> console.log(console)
undefined
> Console { }
以这种方式对所有浏览器对象起作用;
但是如果我使用自己的对象,输出没有我的objectName(MyObj),只有像这样的Object:
Works in this way for all browser objects; But if I do it with my own object, the output don't have my objectName(MyObj), only "Object" like this:
> var MyObj=function(){}
undefined
> var instance = new MyObj();
undefined
> instance
Object { }
> instance+""
"[object Object]"
> console.log(instance);
undefined
Object { }
有没有办法让我的对象输出行为与浏览器对象相同?并且,任何人都可以解释我为什么?
Is there a way to make my objects output behavior be the same of browser objects ? And, can anyone anyone explain me why ?
推荐答案
你可以覆盖 toString()
中的方法MyObj.prototype
:
MyObj.prototype.toString = function(){ return "[object MyObj]";}
示例
Example
var MyObj = function(){};
MyObj.prototype.toString = function(){ return "[object MyObj]"; };
var instance = new MyObj();
console.log(instance + "");
// "[object MyObj]"
这篇关于js如何将objectName打印到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文