Jon Aquino's Mental Garden

Engineering beautiful software jon aquino labs | personal blog

Saturday, April 26, 2008

[Programming] Understanding the "this" keyword in JavaScript

My colleague asked me how to know what the "this" keyword refers to in JavaScript. It's a bit different from other languages.

First, the rule: When you invoke a function on an object, "this" refers to the object. When you invoke a function by itself, "this" refers to the global object (the window object).

Now for some examples.

Creating an object in JavaScript is easy:
    var food = {};

Let's add a function to this object:
    var food = {
getCalories: function() { alert(this); return 300; }
};

food.getCalories();

When we call food.getCalories(), "this" is the food object, because we are invoking the function on the food object.

But check this out:
    var getCals = food.getCalories;
getCals();

Here we invoke the function by itself, i.e., not on an object. "this" is the global object (i.e. window), because we are invoking the function by itself.

Now look at this:
    var automobile = {};
automobile.getCalories = getCals;
automobile.getCalories();

Here we've created an automobile object, and added our function to it. "this" is the automobile object, because we are invoking the function on the automobile object.

Thus, "this" is a dynamic quantity – it is not cast in stone when the function is defined, but refers to the current object that the function is being invoked on.

3 Comments:

  • Would you consider writing something about the JavaScript "this" keyword for the wikipedia page about "this"? (http://en.wikipedia.org/wiki/This_(computer_science)) Your explanations (particularly the "rule" and "dynamic quantity" parts) were very helpful to me.
    Thanks! ~Aranel Alasse~

    By Anonymous Anonymous, at 3/11/2009 1:32 p.m.  

  • Good idea, Aranel - I've added a link to this page from Wikipedia.

    By Blogger Jonathan, at 3/11/2009 8:45 p.m.  

  • Cool. :)
    Unfortunately, it looks like your link was removed by a wikipedia link-watching BOT (http://en.wikipedia.org/wiki/User_talk:XLinkBot)... I assume that if you put an explanation for "this" directly onto the page (instead of a link), it'll have a better chance of surviving (and perhaps a better chance of being seen/read/helpful--which is the end goal, afterall) --especially if you have some sources that you can cite...
    If you put it on the JavaScript page, I hope you will also consider putting it on the This_(computer_science) page (using "{{main|JavaScript}}").
    Anyways, don't be discouraged, and I hope you try again to get an explanation of "this" onto wikipedia! :)
    (If it helps in formulating your contributions, I posted a couple other links that you can look at on the talk page for "this" http://en.wikipedia.org/wiki/Talk:This_(computer_science))
    Thanks!
    ~Aranel Alasse~

    By Anonymous Anonymous, at 3/12/2009 2:08 p.m.  

Post a Comment

<< Home