Learning Javascript – ‘this’ keyword with examples

By | April 1, 2016

In my previous article I have discussed about the javascript functions. In this article I will continue discussing the use of ‘this’ keyword with code examples and I will also discuss about the bind method which can be used to change the context of execution. The ‘this’ keyword is not same as C#.

Become an Expert in Programming and Web Development.View all courses!

The ‘this’ keyword in Javascript with example

Just like C# we have this keyword in the javascript. In C# this keyword denotes the instance of the current class as shown in the following code snippet.

In the above code I have a private variable defined for the Person class named firstName. In the constructor of the class I have assigned the value of the firstName parameter to the firstName private variable of the class using this keyword.

Since in javascript there are no concept of formal classes. The ‘this’ keyword here denotes the owner of the functions. Have a look at the below figure

'this' keyword in javascript

and the output of this code is the “[object window]” as the MyFunc() is defined at the global scope which is owned by the window object.

Now let’s check the ‘this’ keyword if we are using it inside a function which is again defined in an object. In the below code I have created an object using the object initialization technique

If I check the result of this code I will get the “vikram” as output. In this particular case the owner of the returnName function is the person object and we want to access the name property of person object using ‘this’ keyword.

Now we have a very important function in javascript known as bind() which can be used to change the owner of function. bind can be used to change the owner of the function to the current context where bind is defined.

Please check the below code to make this point clear

In the above code snippet I have changed the scope of returnName function by using the bind. Now as the scope of this is changed to the global scope, the output of the above code will be “Suraj” followed by “vikram” as the scope of only the foo() function is changed and not the returnName function.

By looking at the above example we can clearly confirm that the bind function only changes the context in which the function will be executed and not the original owner of the function.