![](/img/trans.png)
[英]Why js variable show [object object] but console.log() works?
[英]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 () {};
我認為函數foo是一個對象,但為什么Chrome中的console.log顯示"function () {}"
而不是可檢查的對象? 無論如何,在記錄函數時是否顯示可檢查對象?
當您調用console.log(foo)
,控制台會構建一個非規范化的顯示(它不是EcmaScript的一部分)。 在大多數情況下(但不是基本對象),它調用參數的toString
函數(但是更多的工作,比如在字符串中添加引號,設置顏色,提供對象瀏覽等)。
函數的toString
函數只是打印代碼。
如果您想查看所有屬性,您可能會這樣做
console.dir(foo);
或者( 至少在Chrome上 )
console.log("%O", foo);
對於具有專用toString
函數的其他對象,您會看到相同的現象。
例如 :
var a = new Number(3);
a.b = 4;
console.log(a); // logs just 3
console.dir(a); // lets you see b
使用console.dir()
查看a
>>>>console.log(foo);
function()
>>>>console.dir(foo);
a "an attribute"
prototype Object { }
破壞是對的。 function是toString打印代碼的對象。
console.log(foo.a);
會做的伎倆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.