In JavaScript, this is a keyword that refers to the current execution context. The value of this is determined dynamically at runtime, based on how the function is called or how the code is executed.
The usefulness of this lies in its ability to provide a way for a function to access and manipulate properties of the object that it is associated with. In other words, it allows functions to be reused with different objects, without having to hard-code the object references inside the function.
Here is an example of using this to refer to properties of an object:
var person = {
name: "John",
age: 25,
sayHello: function() {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
};
person.sayHello();
// outputs "Hello, my name is John and I am 25 years old."
Constructor function: Use this to refer to the object being created by the constructor function.
Method: Use this to refer to the object that the method belongs to.
function Person(name, age) {
this.name = name;
this.age = age;
}
var john = new Person("John", 25);
console.log(john);
//Person {name: 'John', age: 25}
var person = {
name: "John",
age: 25,
sayHello: function() {
console.log("Hello, my name is " + this.name);
}
};
person.sayHello();
// Hello, my name is John
Event handler: Use this to refer to the element that triggered the event.
Function: Use this to refer to the global object (e.g. window in a browser) when called without an explicit object.
<button onclick="alert(this.innerText)">Click me</button>
function printThis() {
console.log(this);
}
printThis(); // logs the global object (e.g. window in a browser)
Prototype method: Use this to refer to the object that the method is called on.
Explicit binding: Use this to refer to the object passed as the first argument to call, apply, or bind.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log("Hello, my name is " + this.name);
};
var john = new Person("John", 25);
john.sayHello();
// Hello, my name is John
function sayHello() {
console.log("Hello, my name is " + this.name);
}
var person = {
name: "John",
age: 25
};
sayHello.call(person);
sayHello.apply(person);
var sayHelloToJohn = sayHello.bind(person);
sayHelloToJohn();
// Hello, my name is John
// Hello, my name is John
// Hello, my name is John
Arrow functions: Use this to refer to the lexical scope of the arrow function.
Classes: Use this to refer to the instance of the class.
var person = {
name: "John",
age: 25,
sayHello: () => {
console.log("Hello, my name is " + this.name);
}
};
person.sayHello();
// logs "Hello, my name is undefined"
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log("Hello, my name is " + this.name);
}
}
var john = new Person("John", 25);
john.sayHello();
// Hello, my name is John
Object creation: Use this to refer to the object being created by an object creation pattern (e.g. factory pattern).
DOM manipulation: Use this to refer to the element that was clicked or interacted with.
function createPerson(name, age) {
var person = {};
person.name = name;
person.age = age;
person.sayHello = function() {
console.log("Hello, my name is " + this.name);
};
return person;
}
var john = createPerson("John", 25);
john.sayHello();
// Hello, my name is John
<button class="my-button">Click me</button>
<script>
var button = document.querySelector(".my-button");
button.addEventListener("click", function() {
console.log("You clicked the button:", this);
});
</script>
Constructor function with this keyword:
Arrow function with this keyword:
function Car(model, year) {
this.model = model;
this.year = year;
this.getDetails = function() {
return `Model: ${this.model}, Year: ${this.year}`;
}
}
const myCar = new Car("Honda", 2020);
console.log(myCar.getDetails());
// Model: Honda, Year: 2020
const person = {
name: "John",
age: 30,
sayHello: () => {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`)
}
}
person.sayHello();
// Hello, my name is undefined and I'm undefined years old.
Using this in a method:
Using this inside a callback function:
const student = {
name: "Mary",
grades: [90, 80, 95],
getAverage: function() {
const sum = this.grades.reduce((acc, curr) => acc + curr, 0);
return sum / this.grades.length;
}
}
console.log(student.getAverage());
// 88.33
const button = document.querySelector("button");
button.addEventListener("click", function() {
console.log(`Button clicked: ${this.textContent}`);
});
Using this inside a class:
Using this with call() method:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const person = new Person("John", 30);
person.sayHello();
// Hello, my name is John and I'm 30 years old.
const person1 = {
name: "John",
age: 30
}
const person2 = {
name: "Mary",
age: 25
}
function sayHello() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
sayHello.call(person1); // Hello, my name is John and I'm 30 years old.
sayHello.call(person2); // Hello, my name is Mary and I'm 25 years old.
Using this with apply() method:
Using this with bind() method:
const numbers = [10, 20, 30, 40];
function getMax() {
const max = Math.max.apply(null, this);
console.log(`The max number is: ${max}`);
}
getMax.apply(numbers);
// The max number is: 40
const person = {
name: "John",
age: 30,
sayHello: function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const sayHelloCopy = person.sayHello.bind(person);
sayHelloCopy();
// Hello, my name is John and I'm 30 years old.