Explain how "this" works in JavaScript
Answer:
The keyword this in JavaScript refers to the object that is executing the current function. Its value is determined by the context in which the function is invoked, not where it is defined. This can vary based on how and where the function is called.
How this Works:
- Global Context:
- In the global scope,
thisrefers to the global object (e.g.,windowin browsers orglobalin Node.js).
console.log(this); // In browsers, this logs the `window` object
- Inside Functions:
- In non-strict mode,
thisrefers to the global object. - In strict mode (
'use strict';),thisisundefined.
function showThis() {
console.log(this);
}
showThis(); // In browsers: `window` (non-strict), `undefined` (strict mode)
- Inside Methods:
- When a function is called as a method of an object,
thisrefers to the object.
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
},
};
obj.greet(); // Outputs: "Alice"
- Arrow Functions:
- Arrow functions do not have their own
this. They inheritthisfrom the surrounding lexical context.
const obj = {
name: 'Alice',
greet: () => {
console.log(this.name);
},
};
obj.greet(); // Outputs: undefined (inherited from global scope)
- In Constructors:
- Inside a constructor,
thisrefers to the new object being created.
function Person(name) {
this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // "Alice"
- Explicit Binding:
- Using
.call,.apply, or.bind, you can explicitly set the value ofthis.
function greet() {
console.log(this.name);
}
const user = { name: 'Alice' };
greet.call(user); // "Alice"