简体   繁体   English

功能是一个对象吗? 为什么console.log不显示可检查的对象?

[英]is function an object? Why console.log does not show inspectable Object?

var foo = function () {};
foo.a = "an attribute";  // set attribute to prove foo is an object
console.log(foo)  // log shows: function () {};

I thought function foo is an object, but why console.log in Chrome shows "function () {}" rather than an inspectable Object? 我认为函数foo是一个对象,但为什么Chrome中的console.log显示"function () {}"而不是可检查的对象? Is there anyway to show inspectable Object when logging a function? 无论如何,在记录函数时是否显示可检查对象?

When you call console.log(foo) , the console builds a non normalized display (it's not part of EcmaScript). 当您调用console.log(foo) ,控制台会构建一个非规范化的显示(它不是EcmaScript的一部分)。 In most cases (but not for basic objects) it calls the toString function of the argument (but does more work, like adding quotes to string, setting a color, offering object browsing, etc.). 在大多数情况下(但不是基本对象),它调用参数的toString函数(但是更多的工作,比如在字符串中添加引号,设置颜色,提供对象浏览等)。

The toString function of a function simply prints the code. 函数的toString函数只是打印代码。

If you want to see all properties, you might do 如果您想查看所有属性,您可能会这样做

console.dir(foo);

or ( at least on Chrome ) 或者( 至少在Chrome上

console.log("%O", foo);

You'd see the same phenomenon with other objects having a dedicated toString function. 对于具有专用toString函数的其他对象,您会看到相同的现象。

For example : 例如 :

var a = new Number(3);
a.b = 4;
console.log(a); // logs just 3
console.dir(a); // lets you see b

Use console.dir() to see the a 使用console.dir()查看a

>>>>console.log(foo);
function()
>>>>console.dir(foo);
a            "an attribute"
prototype    Object { }

dystroy is right. 破坏是对的。 function is an object whose toString prints the code. function是toString打印代码的对象。

console.log(foo.a); 

would do the trick 会做的伎俩

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM