This is often a misunderstood aspect of Javascript. (and "this", I mean this
)
You can think of this
as another parameter that is passed invisibly to your functions. Therefore, when you write such a function,
function add (a,b) { return a+b; }
you really write
function add(this, a, b) { return a+b; }
Most likely, it is obvious that what is not obvious is exactly what is being transmitted, and is called as "this". The rules for this are as follows. There are four ways to call a function, and each of them binds a different thing to this
.
classic function call
add(a,b);
in a classic function call, this
bound to a global object. This rule is now universally regarded as a bug and is likely to be set to null in future versions.
constructor call
new add(a,b);
in the constructor call, this
sets up a new new object whose internal (and inaccessible) prototype pointer is set to add.prototype
method call
someobject.add(a,b);
in a method call, this
set to some object. it doesn’t matter where you originally defined add, be it inside the constructor, part of a specific prototype of an object, or anything else. If you call the function this way, this
set to any object that you called it on. This is the rule that you control.
call / call application
add.call(someobject,a,b);
in a call / apply call, this
set to everything you pass, to the now visible first parameter of the call method.
what happens in your code:
this.parser.didStartCallback = this.parserDidStart;
while you wrote parserDidStart with the expectation that its this
will be an EpisodeController when you call it ... what actually happens, you are now changing your this
from EpisodeController to this.parser. This does not happen on this particular line of code. The switch does not physically occur until:
this.didStartCallback(this);
where this
in this case is EpisodeParser, and by the time you run this code, you have assigned parserDidStart for the name didStartCallback. When you call didStartCallback here, with this code, you basically say ...
didStartCallback.call (this, this);
by saying this.didStartCallback (), you set it this
to .. well .. this
when you call it.
You should be aware of a function called bind, which is explained here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Bind creates a new function from an existing function whose this
fixed (bound) to any object that you explicitly pass.