intermediate 8 min read
this, Execution Context, call, apply, and bind
In JavaScript, 'this' refers to the object that is executing the current function. Its value is determined at runtime based on invocation context, unless explicitly bound or within an arrow function.
Why it matters in interviews
Misunderstanding 'this' context in callbacks, event listeners, class methods, and higher-order functions is one of the most common causes of runtime TypeError exceptions and interview rejections.
Visual & Interactive Explanation
Explicit Binding vs Lexical Arrow Functions
call / apply
Immediate execution
ExecutionInvokes immediately
Argumentscall: args list | apply: array
ReturnResult of function call
Strengths
- •Direct method borrowing across objects
- •Pass variable argument arrays via apply
Trade-offs
- •Cannot be saved as reusable callback handler
bind()
Deferred bound function
ExecutionReturns new bound copy
CurryingSupports partial argument application
Hard BindingCannot be overridden by subsequent call/apply
Strengths
- •Safe event handler callbacks
- •Permanent context attachment
Trade-offs
- •Allocates a new function wrapper in memory
Arrow Functions
Lexical scope inheritance
this valueInherited from outer scope at creation
prototypeNo prototype property (cannot use 'new')
argumentsNo internal arguments object
Strengths
- •No 'this' loss in async timeouts & promises
- •Clean concise syntax
Trade-offs
- •Cannot dynamically re-bind context with .call/.apply
Code Examples & Implementation
Hard Binding Polyfill (Function.prototype.myBind)
// Polyfill for Function.prototype.bind with partial application and 'new' support
Function.prototype.myBind = function (context: any, ...bindArgs: any[]) {
const originalFn = this;
if (typeof originalFn !== 'function') {
throw new TypeError('Function.prototype.myBind must be called on a function');
}
return function boundFn(this: any, ...callArgs: any[]) {
// If invoked with 'new boundFn()', 'this' should be instance of boundFn
const isNew = this instanceof boundFn;
const targetThis = isNew ? this : context;
return originalFn.apply(targetThis, [...bindArgs, ...callArgs]);
};
};
const user = { name: "Sarah", role: "Staff Frontend" };
function greet(greeting: string, punctuation: string) {
return `${greeting}, ${this.name} (${this.role})${punctuation}`;
}
const boundGreet = greet.myBind(user, "Hello");
console.log(boundGreet("!")); // "Hello, Sarah (Staff Frontend)!"Interview-Ready Answers
'this' is determined at call-time by how a function is invoked. call and apply invoke the function immediately with explicit context (apply accepts arguments array), while bind returns a new permanently bound function.
Official Documentation & Specifications
Follow-up Questions & Deep Dives
🎯 Code Output — What Does This Print?
Question 1medium
const obj = {
name: "Alice",
greet: function() {
console.log(this.name);
},
greetArrow: () => {
console.log(this.name);
},
};
obj.greet();
obj.greetArrow();Question 2hard
const obj = {
name: "Bob",
greet() {
console.log(this.name);
},
};
const fn = obj.greet;
fn();Question 3tricky
function greet() {
console.log(this.name);
}
const bound1 = greet.bind({ name: "First" });
const bound2 = bound1.bind({ name: "Second" });
bound2();Question 4hard
const obj = {
x: 10,
getX() {
return this.x;
},
getXArrow: () => this.x,
};
console.log(obj.getX());
console.log(obj.getX.call({ x: 20 }));
console.log(obj.getXArrow());Question 5medium
function Foo() {
this.value = 42;
return { value: 99 };
}
const f = new Foo();
console.log(f.value);Common Mistakes & Anti-Patterns
- Using arrow functions as object methods where access to sibling properties via 'this' is expected.
- Forgetting that strict mode ('use strict') sets default binding to undefined instead of the window object.
- Attempting to rebind an arrow function using .call() or .apply().
Real-World Architectural Scenario
A junior engineer reports that 'this.setState' inside a standard DOM addEventListener callback is undefined in a legacy component. How do you fix it?
Rate Your Readiness
Rate how comfortably you can explain this in an interview to update your global readiness gauge:
Rate your confidence: