I am new to JavaScript I need some help to understand how this keyword works in JavaScript. When I run the following code it result 2 which is obvious.
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
var a = 'global a';
obj.foo(); // 2
but if I run the following code then wthen print global a instead of obj.a.
function foo(){
console.log(this.a);
}
var obj = {
a:2,
foo:foo
}
var bar = obj.foo;
var a = 'global a';
bar();
please anyone tell me why this print global a?