getit
getit

Reputation: 621

Why isn't the context of 'this' in Javascript not changing in this example?

I am experimenting with the context of 'this' in Javascript and I have a situation that I don't understand.

Based on the way javascript works found from here, I understand that when a function is called on an object, the object is implicitly passed in as the firest parameter (or explicitly when using the call method.

But there are 2 cases that I tried to test that didn't do what I expected. Please look at the 2 lines after //Why doesn't ths work? Why are the follwoing 2 values undefined?

Here is the code in a jsFiddle (also pasted below)

function Beta(c, myValParam) {
  var callback = c;
  this.myVal = myValParam;
  this.RunCallback = function () {
   callback();
  }

  this.ShowVal = function () {
    alert("FROM Beta: " + this.myVal);
  }
}

function Alpha() {
  this.myVal = "Alpha's Property";
  this.ShowVal = function () {
    alert("FROM Alpha: " + this.myVal);
  }
}
a = new Alpha();
a.ShowVal();

b = new Beta(a.ShowVal, "Beta's property passed in");
b.ShowVal();

//Why doesn't ths work? Why are the follwoing 2 values undefined?
b.RunCallback.call(b); //Shouldn't this display the value in b?
b.RunCallback();

b2 = new Beta(function() { return a.ShowVal.call(a); }, "Z");
b2.RunCallback();

EDIT: Thanks to the answers from Quentin, dystroy and dough, I've updated the jsFiddle to show the values produced when the context reverts to the window object

And here is the code with the call to callback.call(this) which fixes the problem I was having

Upvotes: 1

Views: 130

Answers (3)

dough
dough

Reputation: 734

I think your issue is that when you invoke callback you're not passing a context so you're losing this. Try updating RunCallback like this:

  this.RunCallback = function () {
   callback.call(this);
  }

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382092

You forgot one step in the definition of RunCallback :

Replace

callback();

with

callback.call(this);

Upvotes: 1

Quentin
Quentin

Reputation: 943100

Shouldn't this display the value in b?

You are calling (in the context of b) a function which does nothing with this. That function calls callback (which is a copy of a.showVal) in the context of window (the default object).

Upvotes: 2

Related Questions