Intermediate LevelJavaScript & TypeScript
How does the this keyword work in JavaScript in different contexts?
❓ Interview Prompt: Explain the 4 rules of this binding: default, implicit, explicit (call/apply/bind), and new binding, plus arrow functions.
The this keyword is determined dynamically by how a function is called, not where it is declared (except for arrow functions):
4 Binding Rules (in order of priority):
1
`new` Binding:
new Foo() binds this to the newly instantiated object.2
Explicit Binding:
fn.call(ctx), fn.apply(ctx), or fn.bind(ctx) explicitly sets this.3
Implicit Binding: Calling a method on an object (
obj.fn()) binds this to obj.4
Default Binding: Standalone function call (
fn()) defaults to global object (or undefined in strict mode).Arrow Function Exception:
Arrow functions do NOT have their own this; they lexically inherit this from their outer scope.
Code Implementation Example
javascript
const user = {
name: 'Alice',
greet() {
console.log('Hello, ' + this.name);
}
};
user.greet(); // Implicit binding: "Hello, Alice"
const detachedGreet = user.greet;
// detachedGreet(); // Default binding: TypeError in strict mode!
// Arrow function lexical this
class Button {
constructor(label) {
this.label = label;
// Arrow function binds this to Button instance
document.addEventListener('click', () => {
console.log('Clicked ' + this.label);
});
}
}💡Implicit method binding vs detached default binding vs arrow lexical this.
🎯 Interview Key Takeaway
this is determined dynamically at call-time by invocation context, except in arrow functions which use lexical scope.
#this#Context#Binding#Intermediate
Back to all JavaScript & TypeScript Questions→