← Back to libraryQuestion 132 of 468
🟨JavaScriptAdvanced

The 'this' Keyword and Binding (call, apply, bind)

📌 Definition:

'this' is a runtime binding that refers to the object a function is executing in the context of. Its value depends on HOW a function is called, not where it is defined — except for arrow functions, which capture 'this' lexically.

📖 Detailed Explanation:

There are several binding rules, checked in order: (1) new binding — 'this' is the newly created object. (2) Explicit binding — call/apply/bind set 'this' to a given object. (3) Implicit binding — obj.method() sets 'this' to obj. (4) Default binding — a plain function call sets 'this' to the global object (or undefined in strict mode). Arrow functions ignore all of these and inherit 'this' from the enclosing lexical scope, which makes them ideal for callbacks where you want to keep the outer 'this'. call(thisArg, ...args) and apply(thisArg, argsArray) invoke immediately; bind(thisArg) returns a new function permanently bound.

🔑 Key Points:
  • 'this' is determined by the call-site, not the definition
  • call/apply invoke now; bind returns a bound copy
  • Arrow functions capture 'this' lexically (great for callbacks)
  • Losing 'this' when passing a method as a callback is a common bug
🌍 Real-World Example:

In a Page Object class, passing this.clickLogin as an event handler loses 'this'. Binding it in the constructor (this.clickLogin = this.clickLogin.bind(this)) or defining it as an arrow-function class field keeps the class instance as 'this' so this.page still works.

🎯 Scenario-Based Interview Question:

const obj = { name: 'QA', greet() { return 'Hi ' + this.name; } }; const fn = obj.greet; fn(); returns 'Hi undefined'. Why, and give two fixes.