About Me

I'm just someone struggling against my own inertia to be creative. My current favorite book is "Oh the places you'll go" by Dr. Seuss

Wednesday, May 18, 2011

This is so confusing!

this is a frequently misunderstood aspect of Javascript. (and by "this", I mean this)

You can think of this as another parameter that gets invisibly passed in to your functions. So when you write a function like,

function add (a,b) {
return a+b;

you're really writing

function add(this, a, b) {
return a+b;

That much is probably obvious, what isn't obvious is exactly what gets passed in, and named as "this". The rules for that are as follows. There are four ways to invoke a function, and they each bind a different thing to this.

classic function call


in the classic function call, this is bound to the global object. That rule is now universally seen as a mistake, and will probably be set to null in future versions.

constructor invokation

new add(a,b);

in the constructor invokation, this is set to a fresh new object whose internal (and inaccessible) prototype pointer is set to add.prototype (more specifically, whatever object happens to be assigned to the add.prototype property at the time the constructor is invoked)

method invokation


in the method invokation, this gets set to someobject. it doesn't matter where you originally defined add, whether it was inside a constructor, part of a particular object's prototype, or whatever. If you invoke a function in this way, this is set to whatever object you called it on. This is the rule you are running afoul of.

call/apply invokation


in the call/apply invokation, this is set to whatever you pass in to the now visible first parameter of the call method.

what happens in your code is this:

this.parser.didStartCallback = this.parserDidStart;

while you wrote parserDidStart with the expectation that its this would be an EpisodeController when you method invoke it... what actually happens is you're now changing its this from the EpisodeController to this.parser. That's not happening in that particular line of code. The switch doesn't physically happen until here:


where this in this instance is the EpisodeParser, and by the time this code is run, you've asigned parserDidStart to be named didStartCallback. When you call didStartCallback here, with this code, you're essentially saying...


by saying this.didStartCallback() ,you're setting its this to.. well.. the this when you call it.

You should be aware of a function called bind, which is explained here:

Bind creates a new function from an existing function, whose this is fixed (bound) to whatever object you explicitly pass in.

No comments: