1. Global Context (in non-strict mode)
this
refers to the global object (i.e., window
in browsers).
console.log(this);
- Regular function:
this
refers to the global object (or undefined
in strict mode).
function myFunction() {
console.log(this);
}
myFunction();
- Method:
this
refers to the object the method belongs to.
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet();
- Arrow functions do not have their own
this
; they inherit it from the surrounding (lexical) context.
const obj = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};
obj.greet();
- Constructor functions:
this
refers to the new object being created.
function Person(name) {
this.name = name;
}
const person = new Person('Charlie');
console.log(person.name);
call()
/ apply()
: Invoke a function with a specified this
value.
function greet() {
console.log(this.name);
}
const user = { name: 'David' };
greet.call(user);
greet.apply(user);
bind()
: Create a new function with this
set to a specific value.
const greetUser = greet.bind(user);
greetUser();
- In classes,
this
refers to the instance of the class.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(this.name);
}
}
const person = new Person('Eve');
person.greet();
- Inside event handlers,
this
refers to the DOM element the event is attached to.
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this);
});
- Arrow functions and
this
: Arrow functions don't bind their own this
.
- Strict mode: In strict mode (
'use strict'
), this
is undefined
inside regular functions.
- Lost context: When passing methods as callbacks,
this
might not refer to the expected object. Use .bind()
, or () => {}
in the callback.