[Coding] A Brief Note on JavaScript and “this”

Posted by Khatharsis on April 20, 2013

I’m still wrapping my mind around the “this” keyword in JavaScript. I ran into some problems when I was working through some exercises and I realized I just didn’t understand how this worked. I also began to get a little uncomfortable when saw this being used seemingly haphazardly (at least to me since I didn’t understand it all that well) in other people’s code. It was a larger shock when I was going through some old code for a new project and this was being used extensively. At the time, I was working through a tutorial so I was probably more focused on building the content of that tutorial (a game), rather than on understanding the syntax.

I just read this article, which gives a decent overview of how this works. Put simply, this depends on the context in which it is called. If this is used in a function, whatever is calling the function is what this refers to. For example:


function foo() {
  this.a = 5;
}

foo();  // window.a is set to 5

Which brings up another issue of global variables (and is my next step in understanding this and global abatement techniques).

Now compare to:


var obj = {
  a: 1;
  foo: function() {
    this.a = 5;
    return this.a;
  }
};
obj.foo();   // returns 5

Since foo() is being invoked on the obj object, this refers to obj instead of window as in the previous example. One other way of thinking about it is thinking in terms of a conversation and the context in which a particular topic may arise. The example that immediately comes to mind is the recent discussion among programmers regarding PyCon and the perceived sexual connotations that resulted when a female programmer overheard two male programmers discussing a topic and using terms that could easily be taken the wrong way (as was in her case). I won’t go into that discussion here, but regarding this in JavaScript, I’m finding it helps to think about where a function is being called and what’s calling it, what is bringing it up, because that is what gives this its context.

I’m finding this keyword is a particularly tricky topic, but I also get the impression that people who truly understand how it works then understand JavaScript and it’s idiosyncrasies. this works differently in JavaScript compared to Java or C#. this in those languages refer to the current object (often used for class variables, for example) vs. context.