Understanding the JavaScript this Keyword
The this keyword in JavaScript can be tricky to understand. It behaves differently depending on where it is used. Let's explore how this behaves in different contexts.
this Inside Global Scope
When this is used alone in the global scope, it refers to the global object (the window object in browsers).
console.log(this); // window
Here, this.name is the same as window.name.
this Inside Function
When this is used in a function, it refers to the global object (the window object in browsers).
function greet() {
// this inside function
// this refers to the global object
console.log(this);
}
greet(); // Window (global object)
this Inside Constructor Function
In JavaScript, constructor functions are used to create objects. When a function is used as a constructor function, this refers to the object inside which it is used.
function Person() {
this.name = 'Jack';
console.log(this);
}
let person1 = new Person();
console.log(person1.name); // Jack
// Output
// Person {name: "Jack"}
// Jack
this Inside Object Method
When this is used inside an object's method, this refers to the object it lies within.
const person = {
name: 'Jack',
age: 25,
// this refers to the object itself
greet() {
console.log(this);
}
};
person.greet();
// Output
// {name: "Jack", age: 25, greet: ƒ}
// Jack
this Inside Inner Function
When you access this inside an inner function (inside a method), this refers to the global object.
const person = {
name: 'Jack',
age: 25,
greet() {
// this refers to the object itself
console.log(this);
function innerFunc() {
// this refers to the global object
console.log(this.age);
}
innerFunc();
}
};
person.greet();
// Output
// {name: "Jack", age: 25, greet: ƒ}
// undefined
this Inside Arrow Function
Inside an arrow function, this refers to the parent scope.
const greet = () => {
console.log(this);
};
greet(); // Window (global object)
When you use this inside an arrow function, it refers to its parent scope object.
const greet = {
name: 'Jack',
// method
hi: () => console.log(this.name)
};
greet.hi(); // undefined
// Here, `this.name` inside the `hi()` function
// refers to the global object, not `greet` object.
You can also use the arrow function to solve the issue of having undefined when using a function inside a method. Here, innerFunc() is defined using the arrow function. It takes this from its parent scope. Hence, this.age gives 25.
const person = {
name: 'Jack',
age: 25,
greet() {
console.log(this);
const innerFunc = () => {
console.log(this.age);
};
innerFunc();
}
};
person.greet();
// Output
// {name: "Jack", age: 25, greet: ƒ}
// 25
Follow Us:
Stay updated with our latest tips and tutorials by subscribing to our YouTube Channel.