2

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!

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
  • 3
    Because that's how Google Chrome's console logs elements of type `function`. – ibrahim mahrir Sep 14 '17 at 22:14
  • 1
    ... If you want it to show up like an object (so you can see its properties) then use `dir` instead of `log`: `console.dir(func);` – ibrahim mahrir Sep 14 '17 at 22:15
  • @ibrahimmahrir you could also do `console.log(Object.assign({}, func));` – Patrick Roberts Sep 14 '17 at 22:27
  • @PatrickRoberts but that will copy the properties into another object. It won't the function. `console.log([ func ]);` will do fine (an array that contain the function, the function will be listed like an object not as code source). – ibrahim mahrir Sep 14 '17 at 22:29
  • @ibrahimmahrir I'm well aware of what my approach does, but the request was to log the properties, which is exactly what it does. – Patrick Roberts Sep 14 '17 at 22:31

1 Answers1

4

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476