1

I was asking this and it's a little bit confusing... What will be printed on the console.

var a = {
 b : {
  foo : function(){
   console.log(this);
   }
  }
 }

a.b.foo();//in console : foo function

var b = a.b;
b.foo();//in console : foo function

var foo = a.b.foo;
foo();////in console : window

The first one is quite obvious. Why second print is also foo function and third is window object? thanks

eladr
  • 239
  • 2
  • 14

2 Answers2

1

In foo(), the line console.log(this); will log the object that the function belongs to.

You're slightly mistaken about the console.log result for the first two examples. The console.log doesn't log foo(), rather it's logging a.b -- which is the object that foo() belongs too. Try adding console.log(a.b); to your code and you'll see that it logs the same result.

In your third example, window is logged because window is the base scope of all javascript objects. It's automatically "attached" to each variable you define.

So for example:

window.foo = 5;

Is the same as:

var foo = 5;

The first two examples invoke foo() when it's a child of another object so window.foo does not exist.

Elliot B.
  • 14,589
  • 9
  • 70
  • 99
  • This is valid in browsers, but the global object might have another name than `window`, if you are not in a browser. (For example, node.js on server -side) – Pac0 Feb 01 '18 at 07:41
0

The second one use a reference to a.b, so you are still executing in the context of the { a: {b} } object, this is the object.

In the third one you just get a reference to the function itself, attached to a global variable, so no sub-object context when calle. Only the global context (which is windowin a browser console, but not same result for other javascript context, like node.js)

Pac0
  • 16,761
  • 4
  • 49
  • 67