The "this" keyword in JavaScript refers to the object that is currently executing the code.
Its value depends on how a function is called.
1) "this" inside an object
this refers to the current object.
EXAMPLE:
let student = {
name: "Ihsaan",
age: 21,
display: function() {
console.log(this.name);
console.log(this.age);
}
};
student.display();
OUTPUT:
Ihsaan
21
2)"this" in a method
It is commonly used to access the properties and methods of an object.
EXAMPLE:
let car = {
brand: "Toyota",
showBrand: function() {
console.log(this.brand);
}
};
car.showBrand();
OUTPUT:
Toyota
3)"this" in a constructor function
When used with a constructor function, this refers to the new object being created.
EXAMPLE:
function Student(name, age) {
this.name = name;
this.age = age;
}
let s1 = new Student("Ihsaan", 21);
console.log(s1.name);
console.log(s1.age);
OUTPUT:
Ihsaan
21
4)"this" in a class
this is used to access the properties and methods of the current class object.
EXAMPLE:
class Student {
constructor(name) {
this.name = name;
}
display() {
console.log(this.name);
}
}
let s1 = new Student("Ihsaan");
s1.display();
OUTPUT:
Ihsaan
5) "this" in arrow functions
Arrow functions do not have their own this. They inherit this from the surrounding scope.
EXAMPLE:
let student = {
name: "Ihsaan",
display: function() {
let show = () => {
console.log(this.name);
};
show();
}
};
student.display();
OUTPUT:
Ihsaan
Top comments (0)