JavaScript 'this', call, apply and bind Interview Questions
12 interview questions on the JavaScript this keyword with answers and code: the four binding rules, arrow functions, lost this in callbacks, call vs apply vs bind, a bind polyfill, classes and output puzzles.
The this keyword confuses more JavaScript developers than almost anything else, which is exactly why interviewers love it. The good news: this follows a small set of rules. This post covers 12 interview questions on this, arrow functions and call, apply and bind, with explanations you can repeat in an interview.
The rules of this#
Q1. What is this in JavaScript?#
Answer: this is a value that refers to the object a function is working with. For regular functions it is decided at call time, by how the function is called, not where it is defined. Arrow functions are the exception: they don't have their own this and use the one from the surrounding scope.
Q2. What are the four binding rules, and which wins?#
| Priority | Rule | Call looks like | this is |
|---|---|---|---|
| 1 (highest) | new binding | new User() | The newly created object |
| 2 | Explicit binding | fn.call(obj), fn.apply(obj), fn.bind(obj)() | obj |
| 3 | Implicit binding | obj.method() | The object before the dot |
| 4 | Default binding | fn() | undefined in strict mode, the global object otherwise |
"use strict";
function whoAmI() { return this; }
const user = { name: "Asha", whoAmI };
whoAmI(); // undefined (default)
user.whoAmI(); // user (implicit)
whoAmI.call({ id: 7 }); // { id: 7 } (explicit)
new whoAmI(); // whoAmI {} (new)Q3. What is this inside an arrow function?#
Answer: Arrow functions capture this lexically, from the enclosing scope at the time they are created. Calling them with call, apply or bind can't change it, and they can't be used with new.
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // 'this' is timer, inherited from start()
}, 1000);
},
};
const obj = {
name: "obj",
regular() { return this.name; },
arrow: () => this?.name, // 'this' from the module/global scope, not obj
};
obj.regular(); // "obj"
obj.arrow(); // undefinedAn arrow function defined directly in an object literal does not get the object as this. Use method shorthand (regular() {}) for methods and arrows for callbacks inside them.
Q4. Why does this get "lost" when a method is passed as a callback?#
const counter = {
count: 0,
increment() { this.count++; },
};
const inc = counter.increment;
inc(); // TypeError in strict mode: this is undefined
button.addEventListener("click", counter.increment); // this = the button, not counter
setTimeout(counter.increment, 100); // this = undefined (or window)Answer: Implicit binding only applies when the function is called as obj.method(). Assigning or passing counter.increment passes the bare function, so the later call uses default binding (or the caller's own rule, like the event target for DOM listeners).
Fixes: counter.increment.bind(counter), a wrapper arrow () => counter.increment(), or define the method as a class field arrow function.
call, apply and bind#
Q5. What is the difference between call, apply and bind?#
| Method | Runs the function? | Arguments | Returns |
|---|---|---|---|
call | Immediately | One by one: fn.call(obj, a, b) | The function's result |
apply | Immediately | As an array: fn.apply(obj, [a, b]) | The function's result |
bind | No | Optional, pre-filled: fn.bind(obj, a) | A new function with this fixed |
function introduce(greeting, punctuation) {
return `${greeting}, I'm ${this.name}${punctuation}`;
}
const asha = { name: "Asha" };
introduce.call(asha, "Hi", "!"); // "Hi, I'm Asha!"
introduce.apply(asha, ["Hello", "."]); // "Hello, I'm Asha."
const hey = introduce.bind(asha, "Hey");
hey("?"); // "Hey, I'm Asha?"Memory trick: Apply takes an Array; Call takes Commas.
Q6. Give practical uses of call and apply.#
// 1. Borrow a method from another object
const arrayLike = { 0: "a", 1: "b", length: 2 };
Array.prototype.join.call(arrayLike, "-"); // "a-b"
// 2. Spread an array into arguments (pre-ES6)
Math.max.apply(null, [3, 9, 4]); // 9 (today: Math.max(...arr))
// 3. Call a parent constructor (pre-class inheritance)
function Animal(name) { this.name = name; }
function Dog(name) { Animal.call(this, name); this.type = "dog"; }Q7. Can you re-bind a bound function?#
function getName() { return this.name; }
const a = { name: "A" }, b = { name: "B" };
const boundToA = getName.bind(a);
boundToA.call(b); // "A"
boundToA.bind(b)(); // "A"
new (getName.bind(a))(); // new still wins: creates a fresh objectAnswer: No. A bound function's this is permanent; call, apply and a second bind are ignored. Only new can override it, because new binding has the highest priority.
Q8. Write a polyfill for Function.prototype.bind.#
Function.prototype.myBind = function (context, ...presetArgs) {
if (typeof this !== "function") {
throw new TypeError("myBind must be called on a function");
}
const fn = this;
function bound(...laterArgs) {
// If called with new, ignore context and let 'this' be the new instance
const isNew = this instanceof bound;
return fn.apply(isNew ? this : context, [...presetArgs, ...laterArgs]);
}
// Keep the prototype chain so instanceof works with new
if (fn.prototype) bound.prototype = Object.create(fn.prototype);
return bound;
};
function greet(msg) { return `${msg}, ${this.name}`; }
greet.myBind({ name: "Ravi" }, "Hello")(); // "Hello, Ravi"Interviewers look for: returning a new function, partial application (preset args), using apply, and (for bonus points) handling new.
Classes, events and tricky cases#
Q9. How does this work in classes, and why do React class components bind handlers?#
Answer: Class bodies run in strict mode, and class methods live on the prototype. When a method is passed as a callback (like onClick={this.handleClick}), it loses its object and this becomes undefined.
class Toggle {
constructor() {
this.on = false;
this.flip = this.flip.bind(this); // option 1: bind in constructor
}
flip() { this.on = !this.on; }
toggle = () => { this.on = !this.on; }; // option 2: class field arrow
}Class field arrows create one function per instance (more memory), while prototype methods are shared; both are acceptable answers.
Q10. What is this inside a DOM event listener?#
button.addEventListener("click", function (e) {
console.log(this === e.currentTarget); // true: the element the listener is on
});
button.addEventListener("click", (e) => {
console.log(this); // outer scope's this, NOT the button
console.log(e.currentTarget); // use this instead
});Inline onclick="..." attributes also set this to the element.
Q11. Predict the output.#
const obj = {
name: "outer",
inner: {
name: "inner",
getName() { return this.name; },
},
};
console.log(obj.inner.getName()); // ?
const fn = obj.inner.getName;
console.log(fn()); // ? (non-strict script)
console.log((0, obj.inner.getName)()); // ?Answer:
"inner": implicit binding uses the object directly before the dot,obj.inner.undefined(or""in a browser wherewindow.nameexists):fn()is a plain call, sothisis the global object.- Same as the previous line: the comma operator returns the bare function, so implicit binding is lost.
Q12. Predict the output.#
const user = {
name: "Asha",
greetLater() {
setTimeout(function () {
console.log("A:", this?.name);
}, 0);
setTimeout(() => {
console.log("B:", this.name);
}, 0);
},
};
user.greetLater();Answer: A: undefined (the regular callback is called by the timer with default binding) and B: Asha (the arrow inherits this from greetLater, which was called as user.greetLater()).
Quick revision#
| Situation | this |
|---|---|
obj.fn() | obj |
fn() | undefined (strict) / global |
new Fn() | New instance |
fn.call(x) / apply(x) / bind(x) | x |
| Arrow function | Inherited from the enclosing scope |
| DOM listener (regular function) | event.currentTarget |
Next, practise closures and scope interview questions or review the broader top JavaScript interview questions.
Key takeaways#
- For regular functions,
thisis decided by how the function is called, not where it is defined. - Priority: new, then explicit (call/apply/bind), then implicit (obj.method()), then default.
- Arrow functions have no own
this; they inherit it lexically and can't be rebound. callandapplyinvoke immediately (commas vs array);bindreturns a new permanently bound function.- Passing a method as a callback loses its object; fix it with bind, a wrapper arrow or a class field arrow.