Before attempting to solve the below, read this.

Consider the code below:

function Foo1() {
  this.foo = "foo1";

  this.alertFoo = function() {
    alert(this.foo);
  }
}

function Foo2() {
  this.foo = "foo2";

  this.alertFoo = function() {
    alert(this.foo);
  }
}

function moo() {
  var foo1 = new Foo1();
  var foo2 = new Foo2();
  foo1.alertFoo = new Foo2().alertFoo;
  foo1.alertFoo();
}

What will be alerted when the function moo is called?
foo1.

The way “this”(context) is treated in JavaScript explains this behaviour.

When you say foo1.alertFoo = new Foo2().alertFoo, “this” of alertFoo no longer points to foo2’s this but to foo1’s this, because now the function alertFoo is executed in foo1’s context and not foo2’s.

Advertisements