1

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?

Julio Betta
  • 2,275
  • 1
  • 25
  • 25
Torikul Alam
  • 461
  • 1
  • 9
  • 15

2 Answers2

0

In you first example, when you call the function foo on the variable obj, the context of this is the obj itself. That's why a == 2. Now, when you reference the function foo to the variable bar, the context of this is the global window, and the variable a in this context is global a. In this case, to make the function foo behave the same way as in the first example, you can bind it to the obj context. Like this:

function foo(){
  console.log(this.a);
}

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

// bind the context to obj
var bar = obj.foo.bind(obj);
var a = 'global a';

bar();

I hope I could make myself clear... ;)

Julio Betta
  • 2,275
  • 1
  • 25
  • 25
-1

On the first code obj has its own a variable and foo() function is called on obj.
On your second example you are only giving bar a reference to the function so when it is called it prints the member variable of the class, in this case a = global a

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Shinz6
  • 147
  • 1
  • 2
  • 10