Friday, March 11, 2011

Javascript: Changing what this means inside a function

Note: This is a slightly re-worked post from a few years ago that I put on my old blog.
Update 2011-03-12: Very helpful page generally, helpful section Javascript Garden: How this works

I was wondering one day how you could change what this refers to as sometimes you don't want it to refer to the current function, but to some other function (or object or whatever you want to call it.)

Here is a little example: (here's a link to it on jsFiddle)

function container() { 
    this.stuff = "This is the value of container.stuff"; 
    this.otherStuff = { 
        stuff: "This is the value of container.otherstuff.stuff" 
    };

    function alertThis() { 
        alert(this.stuff); 
    }

    alertThis();
 
    alertThis.call(otherStuff);
}

container();

So we define a variable on the container function called stuff and assign the string "This is the value of container.stuff" to it... Fairly simple there!

Then we assing a new object to another variable on the container function. the variable is called otherStuff. The new object also has a variable called stuff which is assigned the string "otherStuff".

The alertThis() function is then defined. It gets the stuff variable from the this object.

Now we have two calls to alertThis(). The first one simply calls the function. So inside alertThis() the this variable refers to the container function. In other words this.stuff is the same as calling container.stuff, which returns "stuff".

The second call to alertThis() is done by calling the call() method on the alertThis() function and passing in a value. The otherStuff argument (what is passed to call()) becomes the value of this inside the called function. So this.stuff is the same as calling otherStuff.stuff which returns the string "This is the value of container.otherstuff.stuff".

Clear as mud?

No comments:

Post a Comment