All about "this" keyword in JavaScript
In this article, we will learn about what is “this” keyword in JavaScript, four different binding of “this” keyword and about “new” keyword.
The this keyword allows you to reuse functions with different contexts. this keyword refers to an object, that object which is executing the current bit of javascript code.In other words, every javascript function while executing has a reference to its current execution context, called this. Execution context means here is how the function is called
In the above code snippet, this refers to the "name" object and hence printing fname and lname in the console.
Default or Implicit Binding
- If we are in strict mode then the default value of this keyword is undefined otherwise this keyword act as global object, it’s called default binding of this keyword.
- when there is an object property which we are calling as a method then that object becomes this object or execution context object for that method, it is implicit binding of this keyword.
In order to figure out what the this keyword is referencing, first, look to the left of the dot when the function is invoked. If there is a “dot”, look to the left of that dot to find the object that the this keyword is referencing. In the example above, name is to “the left of the dot” which means the this keyword is referencing the name object. So, it’s as if, inside the fullNamemethod, the JavaScript interpretor changes this to name.
Explicit Binding
If we use call, apply or bind method with calling function, all of those methods take as their first parameter as execution context. that is this binding.To get a grasp of "call, apply and bind" method, read my post Understanding Call, Apply and Bind Methods in JavaScript
new Binding
The third rule for figuring out what the this keyword is referencing is called the new binding. If you’re unfamiliar with the new keyword in JavaScript, whenever you invoke a function with the new keyword, under the hood, the JavaScript interpretor will create a brand new object for you and call it this. So, naturally, if a function was called with new, the this keyword is referencing that new object that the interpretor created.
So putting all of our rules into practice, whenever I see the this keyword inside of a function, these are the steps I take in order to figure out what it’s referencing.
- First it checks whether the function is called with new keyword.
- Second it checks whether the function is called with call(), apply() or bind() method means explicit binding.
- Third it checks if the function called via context object (implicit binding).
- Default global object (undefined in case of strict mode).
That's all for now. Thank you for reading and I hope this post will be helpful :)







