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,
this
refers to the global object (e.g.,window
in browsers orglobal
in Node.js).
console.log(this); // In browsers, this logs the `window` object
- Inside Functions:
- In non-strict mode,
this
refers to the global object. - In strict mode (
'use strict';
),this
isundefined
.
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,
this
refers 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 inheritthis
from 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,
this
refers 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"