Introduction
The this keyword is one of the most confusing concepts in JavaScript. Many developers struggle with the concept of this.
However, understanding the concept of this
is crucial for learning object-oriented programming (OOP) in JavaScript.
In this article, I will explain what the concept of this is and how it is used in different contexts.
What is this
?
In simple terms, this refers to an object. this
makes it convenient to reference objects. Without this
, referencing an object would be difficult as you'll need to write more code. This can make your code error-prone.
The object this
refers to, depends on the context in which this was called.
Let's look at the different contexts this can be called in JavaScript:
Object method
When used in an object method, this refers to the object that bears the method.
const person = {
name: "John Doe",
greet() {
console.log(`Hello, my name is ${this.name}`);
},
};
person.greet(); // Hello, my name is John Doe
In the code above, this refers to the person object.
Constructors
In constructor functions, this refers to the new object instance created by the constructor function.
class Toyota {
constructor(model) {
this.model = model;
}
}
const toyota = new Toyota("Camry");
console.log(toyota.model); // Camry
In the code above, this
refers to the toyota instance.
Functions
In a function, the this keyword refers to the object calling the function.
If the function is called in the global scope, this refers to the global object.
function greet() {
console.log(this); // window object
}
greet();
In the above code, this
refers to the window
object.
Note: In the browser, the global object refers to the
window
object. In Node.js, the global object refers to theglobal
object.
If the function is an object method, this
refers to the calling object.
const person = {
name: "John Doe",
greet() {
console.log(this); // person object
},
};
person.greet();
In the code above, this
refers to the person object.
In strict mode, this
returns undefined
.
"use strict";
function greet() {
console.log(this); // undefined
}
greet();
Arrow functions
Arrow functions, introduced in ES6, are a more concise way of declaring functions. Arrow functions provide a more shorter syntax for declaring functions.
// Traditional function
function greet() {
console.log(this);
}
// Arrow function
const greet = () => {
console.log(this);
};
Unlike in regular functions, this
works differently in arrow functions.
In an arrow function, this
refers to the owner of the function—context/scope where the arrow function was declared. This is because in arrow functions, there's no binding of this
.
In the code below, the arrow function is declared in the global context/scope, and so this refers to the global object, window
, in this case.
const greet = () => {
console.log(this);
};
greet(); // window object
If you try to attach the function to an event handler, the greet()
function will still refer to the window
object. See below.
<button>Click Me</button>
<p id="paragraph"></p>
const button = document.querySelector("button");
const greet = () => {
document.getElementById("paragraph").innerText += this;
};
button.addEventListener("click", greet);
Event handlers
Event handlers are functions that handle HTML events. HTML events are actions carried out by the browser or user. HTML events include but are not limited to the following:
- Page load
- Button click
- Page scroll
In event handlers, this
refers to the object receiving the event.
For example, in this code, this
refers to the HTML button element, since it's the object receiving the onclick
event:
<button onclick="greet()">Click me!</button>
<p id="paragraph"></p>
function greet() {
document.getElementById('paragraph').innerText += this; // button element
}
Explicit binding
You can explicitly specify the object you want this to refer to. JavaScript provides three built-in methods (call()
, apply()
, bind()
) that help you specify the object you want this to refer to.
call()
and apply()
These two methods allow you to borrow a method from another object.
const person1 = {
name: "John Doe",
greet: function (){
console.log(`Hello, I'm ${this.name}`);
}
}
const person2 = {
name: "Susan Doe"
}
// using call()
person1.greet.call(person2); //Hello, I'm Susan Doe
// using apply()
person1.greet.apply(person2); //Hello, I'm Susan Doe
The call()
and apply()
methods are identical in functionality. The only difference between the two is that call()
accepts a list of arguments while apply()
accepts an array of arguments.
bind()
The bind()
method works pretty much the same way as call()
and apply()
methods. The difference is that the bind()
method returns a function while call()
and apply()
returns the result of calling the function.
const person1 = {
name: "John Doe",
greet: function (){
console.log(`Hello, I'm ${this.name}`);
}
}
const person2 = {
name: "Susan Doe"
}
const greetPerson2 = person1.greet.bind(person2);
greetPerson2(); // Hello, I'm Susan Doe
Conclusion
In this article, you have learned about the this
keyword in JavaScript. You have seen how this
can be used in different contexts, such as object methods, constructors, functions, and event handlers. You have also seen how this
works differently in arrow functions.
The this
keyword is a powerful tool in JavaScript, but it can also be confusing. I hope this article has helped you to better understand how this
works and how to use it effectively in your code.
If you have any questions or feedback about this article, please feel free to leave a comment below.
You can also connect with me on LinkedIn and X (formerly Twitter)
Additional resources
- MDN—this in JavaScript
- Understanding this in JavaScript | How to implement it—Simplilearn
- How to use this keyword in JavaScript—freeCodeCamp
FAQs
Can I change the value of this?
No. this
is a keyword and like any other keyword, you can't change the value of this
. Rather, you can use bind()
, call()
, or apply()
to explicitly specify the object this
references.
Can I use this
in strict mode?
It is not recommended. Using this
in strict mode returns undefined
, which can lead to bugs in your code.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.