How is the 'this' keyword determined in JavaScript and how do call, apply, and bind work?
The value of `this` inside a function is determined by **how the function is called** (its execution context), not where it was declared:
1. Method invocation (`obj.fn()`): `this` refers to `obj`. 2. Standalone function call (`fn()`): `this` refers to the global object (`window`/`global`), or `undefined` in strict mode. 3. Constructor call (`new Fn()`): `this` refers to the newly instantiated instance. 4. Arrow functions: Do not have their own `this`; they capture `this` lexically from their enclosing scope.
`call` and `apply` invoke a function immediately with an explicit `this`. `bind` returns a new function with `this` permanently locked.
const user = {
name: "Morgan",
greet(punctuation) {
return `Hello, ${this.name}${punctuation}`;
}
};
const admin = { name: "Taylor" };
// 1. call: passes arguments individually
console.log(user.greet.call(admin, "!")); // "Hello, Taylor!"
// 2. apply: passes arguments as an array
console.log(user.greet.apply(admin, ["?"])); // "Hello, Taylor?"
// 3. bind: creates a new function with bound context
const boundGreet = user.greet.bind(admin, ".");
console.log(boundGreet()); // "Hello, Taylor."`bind` is especially vital when passing methods as event listeners or timers, preventing `this` from detaching and defaulting to `undefined`.
Ready for Hoisting & TDZ?
Take a quick test to evaluate yourself, or move straight to the next module.