Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 944
Helin Wang Avatar asked Apr 11 '26 23:04

Helin Wang


1 Answers

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
like image 166
Denys Séguret Avatar answered Apr 13 '26 14:04

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!