Tutorial Playlist
The word this might seem simple at first, but according to me, it is a surprisingly nuanced part of JavaScript. I believe that mastering JavaScript this keyword is essential for writing clean, predictable JavaScript code.
The ‘this’ keyword within a JavaScript function refers to the current execution context. This context can change depending on how the function is called.
Let's dive into how this works, its common pitfalls, and how to use this effectively. We will also explore various scenarios in this tutorial and understand the different applications of JavaScript this keyword.
In essence, this refers to the object that a function is currently being executed within. The value of this is determined not by where the function is defined, but by how it's called. This dynamic nature can be both powerful and confusing if not fully understood.
Here are some common scenarios where JavaScript this keyword is used:
Let's delve into the various techniques you can use to control the value of 'this' in JavaScript for precise and predictable code behavior:
1. call() and apply()
The call() and apply() methods allow you to explicitly set the value of ‘this’ when calling a function. apply() takes an array of arguments, while call() accepts arguments individually.
Syntax:
|
Example:
Code:
|
Note: JavaScript const is a JavaScript keyword for declaring constants.
2. bind()
bind() creates a new function with this permanently bound to a specific value. This method returns a new function, rather than immediately executing the original function.
Syntax:
const newFunction = originalFunction.bind(thisValue);
newFunction();
Example:
Code
const pet = { name: "Fluffy"};
function petIntro() {
console.log(`My name is ${this.name}`);
}
const boundIntro = petIntro.bind(pet);
boundIntro(); // Output: My name is Fluffy
3. Arrow Functions
Inherit this from the enclosing lexical scope. Arrow functions provide a more predictable and concise way to manage this.
Syntax:
|
Example:
Code:
const myObject = {
counter: 0,
logger: () => {
console.log(this.counter); // 'this' refers to myObject
}
};
4. Strategic Use of JavaScript this keyword (Combination Strategies)
Often, the best approach for controlling this includes a combination of these techniques. Consider the following scenario within a class:
Example:
Code:
|
Code:
|
Here, person.greet() is called. Since greet is a method defined within the person object, this inside greet refers to person itself. This allows you to access the object's properties (like name) within the method.
Code:
|
When you call announce() without being part of an object, this often defaults to the global object, which is window in a browser environment. This can lead to unexpected behavior if you intend this to reference a specific object. Learning JavaScript with keywords is essential to avoid these types of unexpected instances.
Code:
|
When you use new with a function like Car, this inside the function refers to the newly created object (myCar in this case). This allows you to assign properties (like model and year) and methods (like getInfo) to the new object instance.
Note: JS new keyword is a JavaScript keyword for declaring constants.
Within event listeners (addEventListener), this refers to the DOM element that triggered the event.
Example HTML:
|
Example JS::
|
In this case, clicking the button makes this point to the <button> element itself.
Code:
|
The constructor function is called when you create an object using new. this within the constructor refers to the newly created object, allowing you to set its properties. Inside methods like getDetails(), this refers to the specific object instance (myCar in this case).
Here are some advanced techniques for managing JavaScript this keyword:
Problem:
Solution A: {Replacing the existing
setTimeout()
function}
setTimeout(() => { // Arrow function inherits 'this'
this.seconds++;
console.log(this.seconds);
}, 1000);
Fixed code:
Code:
|
Solution B: {Replacing the existing
setTimeout()
function}
setTimeout(function() {
this.seconds++;
console.log(this.seconds);
}.bind(this), 1000);
Fixed code:
Code:
|
If you wish to learn web development and tools such as JS, you can check out upGrad’s full stack development courses.
Code:
|
Inside fullName, this refers to the person object, allowing you to access its properties (firstName and lastName) using dot notation.
Code:
|
This is a tricky one because innerFunction is defined within getValue, it doesn't inherit this from myObject. Here, this inside innerFunction would likely refer to the global object (window). To fix this, you can use techniques like bind() or arrow functions to ensure innerFunction uses the correct this value.
The this keyword is fundamental for building real-world JavaScript applications. Here are some applications of this:
The this keyword in JavaScript serves as a vital reference to the current execution context. Understanding how its value is determined within different scenarios is fundamental to writing well-structured object-oriented JavaScript code. While the default behavior of JavaScript this keyword can sometimes be surprising, techniques like call(), apply(), bind(), and arrow functions provide the necessary tools to gain precise control.
If you wish to learn JavaScript and other essential tools you will need as a developer, you can enroll in upGrad’s software engineering courses.
1. Why use this keyword in JavaScript?
The this keyword is used in JavaScript to access and manipulate properties and methods within an object's context or the current execution context. This is essential for object-oriented programming and working with dynamic data.
2. Why this keyword is not mostly used in JavaScript?
The this keyword is widely used in JavaScript, especially in OOP and event handling. However, the dynamic nature of JavaScript this keyword can lead to confusion if not understood properly.
3. How to bind the this keyword in JavaScript?
You can bind JavaScript this keyword using the following methods:
4. How to avoid this keyword in JavaScript?
You can sometimes avoid using JavaScript this keyword by:
5. What is the scope of this in JavaScript?
The scope of JavaScript this keyword is determined by how a function is called, not where it's defined. Its value can change depending on the context.
6. Can we use this in arrow function?
Yes, but arrow functions behave differently than regular functions regarding this. Arrow functions inherit this from their enclosing (lexical) scope, providing more predictable behavior and often reducing the need to explicitly bind this.
mukesh
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .