Q:

"this" context output not able to understand

I am facing difficulty understanding the below code.
function foo() {
    console.log( this.a );
}

var obj = {
    a: 2,
    foo: foo
};

var a = 4;

obj.foo();
setTimeout( obj.foo, 100 );
setTimeout( obj.foo.bind(obj), 100 );

Its output comes as 2, 4, 2 which I am not able to understand.

A:

The first case,
obj.foo();

Where the this inside of foo will point obj since you have assigned the function as a property of that particular object.
The second case,
setTimeout( obj.foo, 100 );

In setTimeout, the passed function will be evaluated in the window's context. So here var a = 4; was executed in window's context and became the property of window. when accessing this inside the function foo, that would point to window at this particular situation.
The third case,
setTimeout( obj.foo.bind(obj), 100 );

You just bound the obj as this to the function foo. And even though the function evaluated in window's context, the bound this value won't be changed. That is the rule behind bind function. So the this won't be changed from obj to window here.

