Rrmm Rrmm - 3 months ago 8
Javascript Question

Confused by Javascript's this behaviour in a particular situation

I'm confused by what happens with this in this simple code:

function foo() {
alert(this.a );
}

function doFoo(fn) {
a = "local";
fn();
}

var a = "global";

doFoo( foo );


From what I've learned, deFoo is the context object from which foo is called so the alert's message should be "local". That works, unless I declare a inside doFoo:

function doFoo(fn) {
var a = "local";
fn();
}


Now the alert message is "global". Can someone explain this to me? I'm new to Javascript.

Answer

Few things to be considered:

  1. value of this is determined by how function is called!
  2. If function is called under the global-context, this refers to window (in browser)
  3. If variable is not defined using keyword var, it is global variable.

In your example, a inside function doFoo refers to window.a which is local, overwritten when function is invoked.

function foo() {
  alert(this.a);
}

function doFoo(fn) {
  console.log(window.a);
  a = "local"; //window.a is set to "local"
  fn();
}
var a = "global"; //window.a is "global"
doFoo(foo);

//Few logs to make it clear

console.log(window.doFoo);
console.log(window.a);