?this? keyword in JavaScript
Posted by Superadmin on May 02 2023 15:44:48

“this” keyword in JavaScript

By Priya PedamkarPriya Pedamkar
  

this keyword in JavaScript

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

Why Use “this” Keyword in JavaScript?

How to use “this” Keyword?

It has various values depending on where we use it, for example:

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.