Portfolios that get you hired. Find out more...

When JavaScript this starts to get weird…

“If you put me in time out, I will act strange…” said this.

Just like anyone, this seems a bit unhappy when you put it in time out. Or setTimeout to be precise. If you’ve ever tried to use this with setTimeout you know that it acts a bit weird. Or, does it?

First, we will create another method, just for fun. Here it is:

Person.sayHobby = function(){

Imagine that you want to call the sayHobby method but only after a period of time. Let’s go with 3 seconds. So you write the following code:

//Remember, we state the time in milliseconds
setTimeout(Person.sayHobby, 3000); 

You might expect the output to say ‘running in circles’. But instead, it says… undefined! What happened?

Let’s try one more thing. This time, use the showMeThis method to find out what this actually is in this case. Here we go.

setTimeout(Person.showMeThis, 3000);

So you wait three seconds. And then it turns out that this is pointing to the window object. Not Person as you may have expected.

If you recall, we said that:

Normally, this points to the object that called the method in which it is found.

That implies that window called our method. Which, in fact, is the truth. To see why this happened, you need to go a bit under the hood.

When you use a method with setTimeOut, JavaScript doesn’t call that method directly. It “copies” the method and attaches it to the window object. So, in effect, it’s the window object that calls your method - not the Person object. Since window doesn’t have a property called hobby, you get undefined as a result.

So, this is simply pointing to the object that called it. In this case, it’s the window object. Hmm…

Take moment to digest the above information. Then, try the exercise below.

Exercise 3

Create an object of your choice. Add a method that outputs this into the console. Then, use setTimeOut to call the method after 1 second.

What happened?

It’s time to tame the fire-spitting beast. We will force this to behave itself. We’re going to use our special powers to make sure it points to the object you want. Get ready, you’re going to learn how to bind this.

Next: Behold, I bind this fire-spitting beast…

Self-taught developers: tips for writing code that gets you hired! Join now!