From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this.
Function context
Inside a function, the value of this depends on how the function is
called.
Simple call
function f1(){
return this;
}
f1() === window; // global object
This is what you are doing in the 2nd case b()
. You are basically calling x on the global object. So
var x = 456;
// this.* fail
a = { x : 123, f : function(){ console.log( this.x ) } }
a.f() // 123
b = a.f // b points to a.f now
b() // prints 456
As an object method
When a function is called as a method of an object, its this is set to
the object the method is called on.
In the following example, when o.f() is invoked, inside the function
this is bound to the o object.
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f()); // logs 37
This is what happens in the first case.