JavaScript `this` Binding: Interview Guide
JS جاوااسکریپت

JavaScript `this` Binding: Interview Guide

Master implicit, explicit, and arrow-function `this` rules with classic output questions interviewers love.

BugCast Admin··۵ دقیقه مطالعه

Understanding how this is determined is one of the most common JavaScript interview topics. The answer always depends on how the function is called, not where it is defined.

Common Interview Questions

Q: What are the four rules that determine this?

Answer: Default binding (global/undefined in strict mode), implicit binding (object method call), explicit binding (call/apply/bind), and new binding (constructor call). Arrow functions ignore these and inherit this lexically from the enclosing scope.

Q: What's the output?

Answer: BugCast then undefined (or global property in non-strict). Arrow functions do not get their own this; greetArrow captures outer this, not obj.


const obj = {
  name: "BugCast",
  greet() { return this.name; },
  greetArrow: () => this?.name,
};
console.log(obj.greet());
console.log(obj.greetArrow());

Q: How does bind differ from call?

Answer: call invokes immediately with a provided this and arguments. bind returns a new function with permanently bound this (and optionally partial arguments) without calling it yet.


function greet(greeting) {
  return `${greeting}, ${this.name}`;
}
const user = { name: "Alex" };
greet.call(user, "Hi");
const bound = greet.bind(user, "Hello");
bound();

Q: Why do class methods need binding in React class components?

Answer: When you pass this.handleClick as a callback, it is invoked without the class instance as receiver, so this is lost. Fix with arrow class fields, bind in the constructor, or pass an inline arrow wrapper.

Key Points for Interviews

  • this is determined at call time for regular functions

  • Arrow functions inherit lexical this and cannot be rebound

  • Losing this is common when passing methods as callbacks

  • Use bind/call/apply for explicit control

  • In strict mode, default this is undefined, not window

#this#binding#interview

مطالب مرتبط