The JavaScript 'this' Keyword Explained: Complete Guide
Direct Answer & Key Concept
In JavaScript, the this keyword refers to the execution context of the currently executing function. Its value is determined dynamically by how a function is invoked, except in arrow functions which bind this lexically.
// Demonstrating 'this' Binding
const account = {
holder: "Alex",
balance: 500,
getBalance() {
return `${this.holder} has $${this.balance}`;
}
};
console.log(account.getBalance()); // "Alex has $500"
// Losing context when assigning method to variable
const unboundGetBalance = account.getBalance;
// console.log(unboundGetBalance()); // TypeError in strict mode
// Restoring context with bind()
const boundGetBalance = account.getBalance.bind(account);
console.log(boundGetBalance()); // "Alex has $500"What is the 'this' keyword in JavaScript?
The this keyword is a special identifier automatically defined in the scope of every JavaScript execution context. Unlike lexical variables that resolve where they were authored on disk, a regular function's this binding is determined dynamically based on how and where the function is called at runtime.
4 Rules of 'this' Binding in JavaScript
JavaScript determines this using four established precedence rules:
| Rule | Invocation Example | What this refers to |
| :--- | :--- | :--- |
| 1. Default Binding | Standalone call: showName() | window (browser) or undefined (in strict mode "use strict") |
| 2. Implicit Binding | Method call: user.showName() | The host object preceding the dot (user) |
| 3. Explicit Binding | func.call(obj), .apply(), .bind() | The specific object passed into the call method |
| 4. new Binding | Constructor: new User() | The newly created instance object |
Explicit Binding: call vs apply vs bind
JavaScript provides three prototype methods to manually define what this points to:
function introduce(greeting, punctuation) {
return `${greeting}, my name is ${this.name}${punctuation}`;
}
const person = { name: "Alex" };
// 1. call: invokes immediately with comma-separated arguments
console.log(introduce.call(person, "Hello", "!")); // "Hello, my name is Alex!"
// 2. apply: invokes immediately with array of arguments
console.log(introduce.apply(person, ["Hi", "."])); // "Hi, my name is Alex."
// 3. bind: returns a new permanently bound function for later invocation
const boundIntroduce = introduce.bind(person, "Hey");
console.log(boundIntroduce("!")); // "Hey, my name is Alex!"
How Arrow Functions Handle 'this'
Arrow functions fundamentally bypass the four rules above. An arrow function does not possess its own this context. Instead, it looks up this lexically from its enclosing parent scope, exactly like a normal variable:
const timer = {
seconds: 0,
start() {
// Arrow function captures 'this' from start() method (timer object)
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
};