this in JavaScriptA comprehensive guide to the this keyword and its behavior
this?
In JavaScript, this is a special keyword that refers to the context in which a function is executed.
The value of this depends on how a function is called, not where it's defined.
Key Point: this is determined at runtime based on the invocation context.
In the global execution context (outside any function), this refers to the global object.
console.log(this === window); // true (in browsers)
In a regular function call, this refers to the global object (or undefined in strict mode).
function myFunc() {
console.log(this); // window (or undefined in strict mode)
}
myFunc();
When a function is called as a method of an object, this refers to the object the method is called on.
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // "Hello, my name is Alice"
When a function is used as a constructor (with the new keyword), this refers to the newly created object.
function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice.name); // "Alice"
Arrow functions don't have their own this context. Instead, they inherit this from the surrounding lexical context.
const person = {
name: 'Alice',
greet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // "Hello, my name is undefined"
// (this refers to the global object)
You can explicitly set the value of this using call(), apply(), or bind().
function greet() {
console.log(`Hello, ${this.name}`);
}
const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };
greet.call(person1); // "Hello, Alice"
greet.call(person2); // "Hello, Bob"
const boundGreet = greet.bind(person1);
boundGreet(); // "Hello, Alice"
| Context | this refers to |
|---|---|
| Global | Global object (window in browsers) |
| Function | Global object (undefined in strict mode) |
| Method | Object the method is called on |
| Constructor | Newly created object |
| Arrow function | Lexical context (where it's defined) |
| Event handler | Element that received the event |