Currently, I am exploring the concept of 'this' in Javascript and have encountered a perplexing situation.
After delving into how JavaScript functions operate as outlined here, I grasped that when a function is invoked on an object, the object is implicitly passed in as the first parameter (or explicitly when using the call
method).
However, there were two cases that I attempted to test which did not yield the results I anticipated. Kindly review the two lines following //Why doesn't this work? Why are the following two values undefined?
You can find the code in a jsFiddle (also provided 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 this work? Why are the following two 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();
UPDATE: Following insights from Quentin, dystroy, and dough, I have made some changes in the updated jsFiddle to demonstrate the values produced when the context reverts to the window object
Additionally, here is the revised code with the call to callback.call(this)
which resolves the issue I was facing