Willem van der Veen
Willem van der Veen

Reputation: 36590

Functions as object in Javascript

Hey guys I'm kind of new to JS and found out that functions are also objects. This means I can add properties to them like this:

 let func = function(){};
 func.foo = "foo";
 console.log(func.foo); // prints foo

However when we now do this:

console.log(func);

It will return (using chrome):

enter image description here

Why does it not show the properties of the object like it usually shows on other type of objects? Also when we for instance try to console.log(Function) it will return the following output:

enter image description here

What is this native code? What I got from other sources was that it is code written in another programming language(C, C++) that programmed the functionality of this constructor.

Thanks in advance!

Upvotes: 2

Views: 51

Answers (1)

Ry-
Ry-

Reputation: 224886

Chrome’s console displays functions’ bodies instead of their properties, because that’s usually more useful. It’s much easier to tell when you don’t use an empty function:

Screenshot of non-empty function in Chrome console

And it’ll indeed substitute in [native code] when there is no JavaScript body to be shown.

As @ibrahim mahrir points out, you can use console.dir(func) to get both the default inspection and an expandable list of properties.

Upvotes: 4

Related Questions