“this” in javascript

In object-oriented languages, like Java, this refers to the instance of the class where you run the method. In javascript this is often also the case, but not always.

In this post we’ll explore some situations. And I give some tips on how to deal with them.

The normal case. The function eat is defined on carrot. And we simply run it. this will refer to the enclosing object, which is carrot, with name “carrot”.

When we define and run eat on the toplevel, this will be the window object, with name “result”.

With the function apply, we can change where the function will run on. This will effectively change the meaning of this.

With bind, we can bind a function to another object. This will create a new function that you’ll have to assign to a new variable. The old function stays the same.
Notice that you cannot override that with apply.

With callback functions, we don’t even need to explicitly use apply to mess things up.

When we use anonymous callback functions inside an object, we have to remember that this does not refer to the object anymore. If we want to use it, we’ll have to assign it to an intermediate variable.

Using this knowledge we can create DSL-like functions with funky usage of this.

But it’s clearer to just use parameters.

And that’s basically the gist of it. You can do lots of funky things with this. But your colleagues (and future you), will be happier if you don’t. Some frameworks with callbacks may use it though, so be alert.

The code also exists onĀ jsfiddle, where you can easily try it out.

Leave a Reply

Your email address will not be published. Required fields are marked *