Helin Wang
Helin Wang

Reputation: 4202

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? Is there anyway to show inspectable Object when logging a function?

Upvotes: 3

Views: 3408

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382404

When you call console.log(foo), the console builds a non normalized display (it's not part of 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.).

The toString function of a function simply prints the code.

If you want to see all properties, you might do

console.dir(foo);

or (at least on Chrome)

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

You'd see the same phenomenon with other objects having a dedicated toString function.

For example :

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

Upvotes: 7

Zo72
Zo72

Reputation: 15345

dystroy is right. function is an object whose toString prints the code.

console.log(foo.a); 

would do the trick

Upvotes: 0

epascarello
epascarello

Reputation: 207537

Use console.dir() to see the a

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

Upvotes: 1

Related Questions