The value of 'this' depends on how a function is called: in a method, it refers to the object; in a regular function, it's the global object (or undefined in strict mode); in arrow functions, it's lexically inherited from the enclosing scope.
'this' binding rules (in order of precedence):
new binding: When called with 'new', 'this' is the newly created object
Explicit binding: Using call(), apply(), or bind() explicitly sets 'this'
Implicit binding: When called as object method, 'this' is the object
Default binding: In non-strict mode, 'this' is global object; in strict mode, undefined
Arrow functions:
Common pitfalls:
// 1. Method call - 'this' is the object
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet(); // 'Alice'
// 2. Function call - 'this' is global/undefined
const greet = obj.greet;
greet(); // undefined (strict) or window.name
// 3. Constructor call - 'this' is new instance
function Person(name) {
this.name = name;
}
const bob = new Person('Bob');
console.log(bob.name); // 'Bob'
// 4. Arrow function - 'this' from lexical scope
const obj2 = {
name: 'Charlie',
greet: () => {
console.log(this.name); // 'this' from outer scope
}
};
obj2.greet(); // undefined (not obj2)