0

For the code below, I provide isShiny for an object obj, it is listed as part of the attribute, which is essentially a key-value pair, where the key is isShiny, value is the anonymous function.

But when I provide isShiny for a function func, what really happened behind the scene? When I print out a function, there is no hint of where the isShiny is.

 var obj ={} //this is an object
    obj.isShiny = function () {
        console.log(this);
        return "you bet1";
    };
    console.log(obj); 

    var func = function () {console.log(this)}; //this is a function
    func.isShiny = function () {
        console.log(this);
        return "you bet1";
    };
    console.log(func);

This is the output for console.log from browser.

enter image description here

william007
  • 17,375
  • 25
  • 118
  • 194
  • Can you please add what are you expecting to have as a result? There is not a specific question at this post. Is the real question a knowledge question (e.g. how JavaScript works?) or is there an issue that you are trying to solve? – mikelamar Sep 27 '15 at 10:14

2 Answers2

3

The reason you're not getting any trace of isShiny when you log the function is purely due to the browser's implementation of console.log, and not related to what's happening behind the scenes in JavaScript. console.log sees that the property is a function and therefore doesn't log it out like a 'normal' object. In this case, console.dir would likely be more useful. For more information about how console.log differs from console.dir, check out this question and its answers.

As you have rightly realised, in JavaScript, a function is essentially nothing more than a callable object - you can assign and access properties just like any non-function object.

Community
  • 1
  • 1
Ed_
  • 18,798
  • 8
  • 45
  • 71
2

Use console.dir instead of console.log and it logs the function object with it's methods and properties.

A related question: What's the difference between console.dir and console.log?

Community
  • 1
  • 1
Ram
  • 143,282
  • 16
  • 168
  • 197