JavaScript this keyword

The this keyword in JavaScript serves as a specific pointer that directs to the object actively running the function. Its value is not constant; instead, it varies based on the context of the function call, rendering it a dynamic reference. This keyword represents a fundamental and robust concept employed to reach the properties and functions of an object, enabling the development of adaptable and repeatable code.

In this section, we will explore the functionality of the "this" keyword through various illustrative examples.

Example:

Let's see a simple example of this keyword.

Example

Example

var address=  

{  

company: "Example",  

city: "Noida",  

state: "UP",  

fullAddress:function()  

{  

return this.company+" "+this.city+" "+this.state;  

}  

};  

var fetch=address.fullAddress();  

console.log(fetch);

Output:

Output

C# Tutorial Noida UP

Various methods can be employed to determine the specific object referenced by the "this" keyword.

Global Context

The global context is the primary setting where code runs, not within any specific function or block. Any variable defined outside a function is part of the global scope. The keyword this points to the global object in a global context. In web browsers, this specifically denotes the window object. On the other hand, in Node.js, the value of this is not defined.

Example:

Let's have an example to understand it.

Example

Example

console.log(this);

Output:

In Node.js , the output will be an empty object.

Within the browser environment, the window object serves as the output.

Example

window

Using this in a Method

Within a JavaScript object method, the keyword "this" represents the object to which the method belongs. This enables the method to interact with the object's properties and methods within its own scope. By using "this", direct access to the object's specific properties and methods is granted from within the functions of the method.

Example:

Let's have an example of it.

Example

Example

const myPerson = {

name: 'Johny',

age: 25,

myGreet() {

console.log ('Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old. ');

}

};

myPerson.myGreet();

Output:

Output

Hello, my name is Johny and I am 25 years old.

Explanation:

Within the code snippet above, an instance called myPerson is established. This instance encompasses two attributes: name set to 'Johny' and age set to 25. Additionally, a function named myGreet is declared within the instance. Within the myGreet function, console.log is employed to display a specific message. In this context, this.name is utilized to access the name attribute of myPerson, while this.age is employed to reference the age attribute of the instance.

Upon invoking the myGreet method using myPerson.myGreet, the method was executed resulting in the following output: "Hello, my name is Johny, and I am 25 years old."

Using this in a Function

The functionality of the 'this' keyword in JavaScript functions is contingent upon the method of its invocation within the JavaScript environment.

Example:

Let's understand this with an example.

Example

Example

function greet() {

    console.log('Hello, my name is ' + this.name);

}



const person = {

    name: 'Amit',

    sayHello: greet

};

const anotherPerson = {

    name: 'Jatin'

};



greet(); 

person.sayHello(); 

greet.call(anotherPerson);

Output:

Output

Hello, my name is undefined

Hello, my name is Amit

Hello, my name is Jatin

Explanation:

In the previously shown example, a function named greet was defined and it made use of this.name. The behavior of this in the function is determined by how the function is invoked, not where it is initially declared. An object called person was created with a property called name and a method sayHello that refers to the greet function.

An additional object was generated under the name of anotherPerson, containing a single property identified as name. In this scenario, the function greet was invoked in a standard manner, not as an object's method. Within non-strict mode, the context of this in a typical function points to the global object. Upon invocation as a standard function (greet), this denotes the global object (or is undefined in strict mode). When invoked as person.sayHello, this references the person object. If invoked using greet.call(anotherPerson), this is explicitly assigned to anotherPerson.

Implicit Binding

When a function is invoked as a method of an object, the keyword "this" points to the object from which the function is called.

Example:

Let's have an example of it

Example

Example

const man = {

name: "Joseph",

age: 21,

myGreet: function () {

         return `Hello ${this.name}, your age is ${this.age}.`

   }

}

console.log(man.myGreet());

Output:

Output

Hello Joseph, your age is 21.

Explanation:

In the previous illustration, an object was instantiated and assigned the identifier "person". This object contains two attributes: name with the value "Joseph" and age set to 21. Additionally, a function named greetPerson was defined to generate a personalized greeting message. Within the greetPerson function, the keyword this points to the person object. The expected output when executing this code snippet is 'Hello Joseph, you are 21 years old.'

Default Binding

When not in strict mode, calling a function on its own causes "this" to refer to the global object (which is "window" in browsers). In a standard function, "this" points to the global object in non-strict mode, but in strict mode, it becomes undefined.

Example:

Let's have an example of it.

Example

Example

var myAge = 22;

function verifyMyAge () {

       return this.myAge;

}

console.log(verifyMyAge());

Output:

Output

Undefined

Explanation:

In the previous instance, a variable called myAge was declared within the present scope. Within this function, an attempt is being made to retrieve this.myAge. The accessibility of this property depends on the method of function invocation.

In this scenario, the absence of the property myAge in the global object is due to its declaration with const. Consequently, this refers to the global object. However, the global.myAge remains undefined since const does not generate a property within the global object.

Arrow Function Binding

Arrow functions do not possess an independent this value. They, in contrast, inherit the this value from the surrounding scope where they were declared. While in traditional functions, the this keyword points to the object that invoked the function, in arrow functions, this keyword does not associate with any specific object. Instead, it captures the value of this from the lexical environment.

Example:

Let's have an example of it.

Example

Example

const myPerson = {

    name: "ram",

    age: 22,

    myGreet : () =>{

        return `Hello, you are ${this.age} years old.`

    }

}

console.log(myPerson.myGreet());

Output:

Output

Hello, you are undefined years old.

Explanation:

In the previous instance, an object was instantiated with the identifier myPerson. This object encapsulates two attributes and a single function referred to as name with a value of "ram", age with a value of 22, and myGreet method. In this scenario, a function named myGreet was defined specifically to generate and output a salutation.

In the code snippet provided, the function myGreet is defined as an arrow function. It's important to note that in this context, the reference to 'this' within myGreet does not point to myPerson. If the code is executed in strict mode, the 'this' keyword will have an undefined value. Consequently, attempting to access this.age within the function will not locate the age property on myPerson object since arrow functions do not establish a new 'this' context. As a result, the output displayed will be 'Hello, you are undefined years old.'

The call and apply methods

The call and apply functions enable the creation of a method that is reusable across various objects.

Example:

Let's have an example.

Example

Example

var emp_address = {  

    fullAddress: function() {  

        return this.company + " " + this.city+" "+this.state;  

    }  

}  

var address = {  

    company:"Example",  

    city:"Noida",  

    state:"UP",  

}  

console.log(emp_address.fullAddress.call(address));   

console.log(emp_address.fullAddress.apply(address));

Output:

Output

C# Tutorial Noida UP

C# Tutorial Noida UP

Explanation:

In the example above, we demonstrate the process of borrowing a function called fullAddress from one object, empaddress, and applying it to a different object, address, using the .call and .apply methods. Two objects are defined for this demonstration. The initial object is referred to as empaddress, which contains a single method named fullAddress. Within this method, there is an attempt to access properties such as this.city and this.state, even though these properties are not present within the object itself.

An additional object called address was generated, containing three attributes: company, city, and state. By employing .call, a function can be invoked with a specific this value, in this case, set to address. Consequently, the values can be retrieved utilizing the this keyword. Hence, the result will be C# Tutorial Noida UP.

The .apply method functions similarly to the .call method, with a distinction in how additional arguments are handled. While the call method passes arguments one by one using .call(obj, arg1, arg2, …), the apply method passes arguments as an array with .apply(obj, [arg1, arg2, …]). When no extra arguments are present in our code, using .apply yields an equivalent outcome.

The bind Method

The bind function was added to ECMAScript 5. It generates a fresh function where the this keyword points to the specified value, along with a specified set of arguments.

Example:

Let's have an example of it.

Example

Example

var lang="Java";  

  function lang_name(call)  

{  

    call();  

};  

  

var obj={  

    

  lang:"JavaScript",  

  language:function()  

  {  

    console.log(this.lang+ " is a popular programming language.");  

  }  

};  

lang_name(obj.language);  

lang_name(obj.language.bind(obj));

Output:

Output

undefined is a popular programming language.

JavaScript is a popular programming language.

Explanation:

In the instance demonstrated earlier, a variable called lang was defined utilizing the var keyword. This variable is considered global and is given the value "Java" as a string. A function named lang_name was established, which takes another function as an argument. This function is utilized as a callback and executed without any specific object context, causing "this" to refer to the global context. Furthermore, an object was constructed containing both a property and a method. The property, named lang, holds the string value "JavaScript", while the method, named language, is employed to print out this.lang + " is a well-known programming language."

Within our codebase, the term "this" pertains specifically to the object obj exclusively when referenced as obj.language. We assign the function obj.language as a callback to langname. While inside langname, it is invoked as a standard function call, rather than obj.language. Under these circumstances, the context of this within language ceases to be obj. In a non-strict mode scenario, this now references the global object. As the global object does not possess a property lang, the outcome is the printing of "undefined is a popular programming language".

Upon the second invocation using .bind, a new function is generated where 'this' is predetermined to be the specified object, unless invoked as a constructor with 'new'. Consequently, when the callback is triggered within 'lang_name', 'this' continues to reference 'obj'. As a result, the output will display 'JavaScript is a popular programming language.'

Benefits of this Keyword in JavaScript

Creating Reusable Code: By utilizing the "this" keyword, we enable the reusability of a function across various scenarios. This keyword dynamically points to different objects, allowing methods to be used on diverse instances efficiently. This approach is particularly beneficial for functions that manipulate an object's data, enabling the definition of a method once and its application to multiple instances.

Contextual Binding in JavaScript is determined by the way a function is called, rather than where it is defined. This dynamic binding feature offers flexibility, enabling functions to adjust their actions depending on the context in which they are invoked.

Managing Event Handling: When dealing with event handling, especially in the context of DOM manipulation, the term this signifies the specific HTML element that initiated the event. Understanding this concept simplifies event handling as it provides a straightforward way to access the target element within the event listener.

Facilitates Object-Oriented Design Patterns: The keyword this plays a crucial role in the implementation of classes and constructor functions by referencing the particular instance under creation or utilization.

Conclusion

The keyword "this" plays a crucial role in JavaScript as it dynamically references the object executing a function or method. Its reference varies based on its context of definition. In methods, it denotes the object itself. In the global scope, it points to the global object, but it can be reassigned using methods like call, apply, or bind. This guide delves into the concept of the "this" keyword in JavaScript through diverse examples and addresses common queries. Understanding the usage of the "this" keyword is essential for developers aiming to create efficient websites.

In JavaScript, the keyword "this" refers to the object that is executing the current code. It allows us to interact with the properties and methods of that object within the present context of execution.

  1. In various contexts, what is the reference of "this"?

In JavaScript, "this" pertains to various contexts as outlined below:

Global scope:

Within the global scope, the keyword this points to the global object, such as window in browsers or global in Node.js.

Object Methods:

When a developer invokes a function as a method of an object, the reference "this" pertains to the specific object.

Regular Functions:

Within a standard function, the term this typically points to the global object in non-strict mode, and to undefined in strict mode.

Constructor Functions:

By employing a function as a constructor with the new keyword, the reference "this" pertains to the freshly generated instance of the object.

Arrow Functions:

Arrow functions do not possess their own binding for the this keyword. Instead, they inherit the this value lexically from the surrounding scope.

Event Handlers:

Within DOM event listeners, the term "this" commonly represents the specific HTML element that initiated the event. How can we manage and manipulate the value associated with this particular element?

The management of this value can be achieved through techniques such as:

The call function is used to execute a function while specifying a particular this value and passing arguments individually.

The apply method allows us to call a function with a specific this value and an array of arguments. This can be achieved by using the apply method.

The bind method creates and returns a new function where the this keyword is permanently bound to a specific value, without executing the function immediately.

  1. Is the object that this refers to always consistent?

The value of "this" in JavaScript is not static; instead, it is determined by the function's execution context. This value varies depending on how the function is invoked.

In JavaScript, the arrow function does not have its own binding for "this."

No, the arrow function in JavaScript does not possess a distinct this binding. Instead, it inherits its this value from its lexical scope.

Input Required

This code uses input(). Please provide values below: