For working professionals
For fresh graduates
More
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:
function.call(thisValue, arg1, arg2, ...);
function.apply(thisValue, [arg1, arg2, ...]);
Example:
Code:
const person = { name: "Maya" };
const robot = { name: "R2D2" };
function sayHello(message) {
console.log(`${this.name} says: ${message}`);
}
sayHello.call(person, "Greetings!"); // Output: Maya says: Greetings!
sayHello.apply(robot, ["Beep boop"]); // Output: R2D2 says: Beep boop
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:
const myObject = {
counter: 0,
logger: () => {
console.log(this.counter); // 'this' refers to myObject
}
};
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:
class Timer {
constructor() {
this.interval = 1000;
}
start() {
// Ensure the correct `this` in the callback
setInterval(() => {
this.tick();
}, this.interval);
}
tick() {
console.log("Time elapsed!");
}
}
Code:
const person = {
name: "Bob",
greet: function() {
console.log("Hello from " + this.name);
}
};
person.greet(); // Output: Hello from Bob
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:
function announce() {
console.log(this); // Might print the window object in a browser
}
announce();
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:
function Car(model, year) {
this.model = model;
this.year = year;
this.getInfo = function() {
console.log("This car is a " + this.model + " from " + this.year);
};
}
const myCar = new Car("Tesla Model S", 2024);
myCar.getInfo(); // Output: This car is a Tesla Model S from 2024
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:
<button id="myButton">Click Me</button> |
Example JS::
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log(this); // Output: refers to the button element
});
In this case, clicking the button makes this point to the <button> element itself.
Code:
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
getDetails() {
console.log(`This is a ${this.brand} ${this.model} from ${this.year}`);
}
}
const myCar = new Car("Ford", "Mustang", 2022);
myCar.getDetails(); // Output: This is a Ford Mustang from 2022
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:
class Timer {
constructor() {
this.seconds = 0;
}
start() {
setTimeout(() => { // Arrow function inherits 'this'
this.seconds++;
console.log(this.seconds);
}, 1000);
}
}
const timer = new Timer();
timer.start();
Solution B:
{Replacing the existing setTimeout() function}
setTimeout(function() {
this.seconds++;
console.log(this.seconds);
}.bind(this), 1000);
Fixed code:
Code:
class Timer {
constructor() {
this.seconds = 0;
}
start() {
setTimeout(function() {
this.seconds++;
console.log(this.seconds);
}.bind(this), 1000);
}
}
const timer = new Timer();
timer.start();
If you wish to learn web development and tools such as JS, you can check out upGrad’s full stack development courses.
Code:
const person = {
firstName: "Alice",
lastName: "Smith",
fullName: function() {
// How can we access firstName and lastName within this function
// to return the full name?
console.log(this.firstName + " " + this.lastName);
}
};
person.fullName(); // Output: Alice Smith
Inside fullName, this refers to the person object, allowing you to access its properties (firstName and lastName) using dot notation.
Code:
const myObject = {
value: 10,
getValue: function() {
function innerFunction() {
console.log(this.value); // What will this print?
}
innerFunction();
}
};
myObject.getValue();
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 Kumar
Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management and Pro…Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.