Updated March 18, 2023
What is “this” keyword in JavaScript?
‘this’ is a keyword used for various purposes in the javascript programming code blocks, as ‘this’ can be used in any line of the program for representing a certain object, class, element, and function as well. There are multiple ways for accommodating ‘this’ keyword in the javascript, such as using it with a field, using it to involve a constructor, fetching the current class instance, and using it as a parameter in a method.
Importance of “this” Keyword in JavaScript
- The ‘this’ object in JavaScript has many important roles and uses. It is primarily used to point to an instance of an object from its own method or constructor. Along with pointing, ‘this’ can also be used to keep track of context execution that is based on where the function is called.
- The next thing about the ‘this’ function in JavaScript is that the link to the Execution Context can change. And lastly, the link to the Execution Context can also be established when it’s referred by a callback function, even though the function is defined inside the constructor object.
Why Use “this” Keyword in JavaScript?
- In JavaScript, ‘this’ keyword is used in many contexts to make the best use of the contexts. Basically, ‘this’ keyword is used to refer to some object or function in JavaScript. As by the word (this) itself, we can understand that it’s referring to something. To understand ‘this’ better in a practical way, we can consider an example Mr. X played Cricket and he won the game.
- So, here in the place of using Mr. X again, we used ‘he’ which is referring to Mr. X only. It’s helping us not to keep mentioning the same thing again and again. Same way, in JavaScript also, we can use ‘this’ function or object to refer some other function or object with the value invokes in that function or object. Usually, ‘this’ is used inside a function or method but it can be used outside the function (under global scope) as well.
How to use “this” Keyword?
- As we know that JavaScript is a Scripting Language so there’s no need for a compilation of the codes, it’s executed in the runtime. It can be executed directly by the Interpreter, line by line. And the environment or the scope in which the JavaScript codes are being executed is called “Execution Context”.
- JavaScript runtime maintains a stack of Execution Contexts and it keeps the current stack on top. The object which is referred by “this” gets changed every time Execution Context is changed.
- Simply, we can assume that when a function is created at the same time a keyword ‘this’ is also being created (behind the scene) that links to the object where the function operates. The ‘this’ keyword works differently in JavaScript from other programming languages.
It has various values depending on where we use it, for example:
- ‘this’ refers to the owner object in a method.
- ‘this’ refers to the global object in the alone situation.
- ‘this’ refers to the global objects in a simple function as well.
- ‘this’ refers to an element in an event that receives the event.
- ‘this’ is undefined in a strict mode function.
1. Used with a field
Example:
Below, ‘this’ refers to an object called the person. And the person is the owner of the method fullName.
Code:
var employee = {
firstName: "Raju",
lastName: "Chaudhury",
id: 123
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
A short example for a form field:
Code:
<form name="TestForm" onsubmit="alert(this.name);return false">
<input type="radio" name="TestRadio" onClick="alert(this.name)">
check to alert this object name
<input type="text" name="TestText">
<p>Put name and check the below radio option to alert your entry</p>
<input type="radio" name="TestSecondRadio" onClick="alert(this.form.TestText.value)">
<p>Check this to alert text field entry</p>
<input type="submit">
<p>Notice onsubmit event handler while opening the form to see the action taken when submit button is clicked</p>
</form>
2. Used to invoke a constructor
Usually, when we use the keyword ‘new’ to create an instance for a function object then we use the function as a constructor.
In the below example, we declare a Bike function and then invoke it as a constructor:
Code:
function Bike(name){
this.name = name;
}
Bike.prototype.getName = function(){
return this.name;
}
var bike = new Bike('Pulsar');
console.log(bike.getName());
In the above example, the new Bike(‘Pulsar’) is a constructor of Bike function. Here, JavaScript creates a new object and puts ‘this’ keyword to the newly created object. So, now we can invoke Bike() as the function or as the constructor. Here, in case we remove ‘new’ keyword then it will show some error as below:
Code:
var bajaj = Bike('Bajaj');
console.log(bajaj.name);
/* It will show as TypeError: Cannot read property ‘name’ of undefined */
That because, this in Bike() function is put to the global object, bajaj.name results undefined.
To make the Bike() function always invoked using constructor, we check at the starting of Bike() function as below:
Code:
function Bike(name){
if( ! (this instanceof Bike){
throw Error("We should use new operator to call a function");
}
this.name = name;
}
There’s a metaproperty known as “new.target” which allows detecting if a function is invoked as a simple invocation or constructor.
Here, we can edit the Bike() function which uses new.target metaproperty as below:
Code:
function Bike(name){
if( ! new.target){
throw Error("We should use new operator to call a function");
}
this.name = name;
}
3. Used to return the current class instance
A class expression is also a way to define a class in JavaScript. It can be named or unnamed as well. The named one is the local to its class body and t can be retrieved by the class properties.
/*example for an unnamed class expression*/
Code:
let Mobile = class {
constructor(cost, weight){
this.cost = cost;
this.weight = weight;
}
};
console.log(Mobile.name); //Output: Mobile
/* example for a named class expression */
Code:
let Mobile = class Mobile2{
constructor(cost, weight){
this.cost = cost;
this.weight = weight;
}
};
console.log(Mobile.name);
Output:
Mobile2
4. Used as a method parameter
When we call a method of an object then JavaScript puts ‘this’ to the object which owns the method.
Example:
Code:
var Bike = {
name: 'Pulsar',
getName: function(){
return this.name;
}
}
console.log(bike.getName()); /*Pulsar*/
Here, this inside getName () method refers to a bike object.
Conclusion
The ‘this’ keyword in JavaScript is a powerful tool that usually helps the developers to refer the properties in specific contexts but at times it might be quite tricky as well when applying through the various levels of scope. The value of ‘this’ can also be set explicitly with the call(), bind() and apply() as well. Usually, the value of ‘this’ is determined by the function’s execution context. Arrow functions usually don’t bind ‘this’ and instead of that ‘this’ is bound lexically.
Recommended Articles
This is a guide to “this” keyword in JavaScript. Here we discuss the importance and how to use “this” keyword in JavaScript along with the example. You may also look at the following articles to learn more –