5 min read
ā¢Question 7 of 50hardHow does the "this" keyword work in JavaScript?
Understanding this binding in different contexts.
What You'll Learn
- How
thisis determined - Different binding rules
- Arrow functions and this
The "this" Keyword
this refers to the object that is executing the current function. Its value depends on how the function is called.
Binding Rules
| Context | this Value |
|---|---|
| Global | window (browser) / global (Node) |
| Object method | The object |
| Constructor | New instance |
| Arrow function | Inherited from parent |
| Event handler | Element that received event |
Examples
code.jsJavaScript
// Object method
const obj = {
name: 'John',
greet() {
console.log(this.name); // 'John'
}
};
// Arrow function (inherits this)
const obj2 = {
name: 'Jane',
greet: () => {
console.log(this.name); // undefined (inherits from parent)
}
};
// Explicit binding
function sayName() {
console.log(this.name);
}
sayName.call({ name: 'Bob' }); // 'Bob'
sayName.apply({ name: 'Alice' }); // 'Alice'
const bound = sayName.bind({ name: 'Charlie' });
bound(); // 'Charlie'