Wednesday, April 14, 2010

JavaScript this keyword

I know this this keyword's (in JavaScript) meaning changes depending on how it's called, considering this class:

function Obj() {
this.item = "contents";
}

and using it like this:

var obj = new Obj();
obj.item += " of this.item"; // item now contains "contents of this.item"

the this. keyword means the object only when it's called with new keyword, which declares it as an object.

Now, if I am to change the object slightly, like so:

function Obj() {
this.item = "contents";
var funct = this.funct = function(){
return this.item;
};
}

I have two functions that should return the item inside the object. var funct should be usable inside the object, and this.funct should be usable outside the object, and do the same thing. Cept, when a function is created with var funct, the meaning of this. changes again. I'm not sure what it changes into, but in the above example, when I call funct() from inside the class, it returns "undefined". Everything makes sense, I'm just not sure what happens to this. in that crazy example. There is a way to fix this. You need to put the function inside of a closure, sending this, and using it as another word. For example:

function Obj() {
this.item = "contents";
var funct = this.funct = (function(obj) { return function(){
return this.item;
};})(this);
}

What this does is, instead of sending a function using the this. keyword inside, it creates an anonymous function, sending the object this, RENAMING it to obj, and returning a new function where this is changed to obj, hiding the double meaning of the this keyword, making it refer to the same thing no matter when and how it's called.

I've been learning the meaning of this, and I thought I had it figured out. This just shows you can never know you know everything, only that you don't know everything, by learning something you didn't know :P

No comments:

Post a Comment