Tuesday, January 19, 2016

The this keyword in javascript explained

this keyword in Javascript is a source for confusion. The confusion is mostly due to the fact that the 'this' keyword is used differently in other languages compared to Javascript.

I was also confused of this (Well I still am sometimes) as I was coming from a C# background where the 'this' keyword meant the current instance of that class.

I hope the following will help someone to avoid the 'this' confusion altogether in Javascript.

Let's take an example,


function bar()
{
    console.log(this.age);
}


So what will be the value of 'this'?

Is it an object or is it referring to the function it self?

What if I told you that you cannot answer this question at all at compile time.

The trick is that the value of 'this' would depend on how the function is called.

e.g 1, (Run this on the browser JS console)

bar();

The output would be undefined.

So what was the 'this' object in the above example ? It was the global object (aka window object in the browser)

So naturally the window object did not have a property named 'age' thus the undefined output.

An easy way to think of this is who is calling the bar() function, if its no one then 'this' is going to be the global object.


e.g 2,

var x = { age : 10 , foo : bar };

x.foo();

The above code will actually call the bar function as foo is pointing to bar.

The output will be 10

So in this example bar is being called by x and thus the 'this' object is the x object.


e.g 3,
var y = { age : 15 };
bar.call(y);

The output will be 15

This is because the call() function explicitly sets the this object to the first argument passed into the call function.


e.g 4,

var z = new bar();

Now the 'this' object will be a brand new object and it will also get assigned to z.
This is because of the nature of the 'new' keyword in Javascript.

So the bottom line is the 'this' keyword will depend on how its containing function is called and look to the left of the function call site to determine 'this'


Hope this helps.