In JavaScript, this refers to the object that is executing the current function.
The value of this depends on how a function is called, not where it is written.
In the global scope, this refers to the global object.
window.console.log(this); // windowWhen used in an object method, this refers to the object itself.
const person = {
name: "Alice",
greet() {
console.log("Hello, I'm " + this.name);
},
};
person.greet(); // "Hello, I'm Alice"this.name points to person.name.
const person = {
name: "Alice",
greet() {
console.log(this.name);
},
};
const sayHello = person.greet;
sayHello(); // undefined (in non-strict mode) or error (in strict mode)this is not bound, so it refers to the global object or undefined in strict mode.
const person = {
name: "Bob",
};
function greet() {
console.log("Hello, " + this.name);
}
greet.call(person); // "Hello, Bob"
greet.apply(person); // "Hello, Bob"
const greetPerson = greet.bind(person);
greetPerson(); // "Hello, Bob"call() and apply() call the function immediately, passing a new this.bind() returns a new function with the bound this.In a constructor function, this refers to the newly created object.
function Car(brand) {
this.brand = brand;
}
const myCar = new Car("Toyota");
console.log(myCar.brand); // "Toyota"Arrow functions don’t have their own this. They inherit this from their parent scope.
const user = {
name: "Alice",
greet: () => {
console.log(this.name); // undefined
},
};
user.greet();Arrow functions are great when you want to preserve the surrounding this.
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
new Timer(); // Correctly logs seconds| Context | this Refers To |
|---|---|
| Global scope | Global object (window) |
| Object method | The object itself |
| Function (non-method) call | Global object or undefined (strict) |
| Constructor function | The new object created |
| Arrow function | Inherits this from outer scope |
With bind(), call(), apply() | Manually defined object |
this to access properties.this.bind() to fix this in a detached function.setTimeout to preserve outer this.this.