Lesson 15 of 80
Three methods every function has for controlling exactly what `this` means when it runs — the manual override for everything the this-binding rules do automatically.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
What's the key difference between `fn.call(obj)` and `fn.bind(obj)`?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
this is normally decided by how a function gets called. call, apply, and bind let you decide it yourself instead — you hand the function a this value explicitly.
const user = { name: "Ada" };
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
greet.call(user, "Hi"); // "Hi, Ada" — calls now, this = user
greet.apply(user, ["Hi"]); // same, but args as an array
const boundGreet = greet.bind(user);
boundGreet("Hi"); // "Hi, Ada" — this is now permanently user
call and apply both invoke the function immediately with a chosen this — they only differ in how you pass the remaining arguments (comma-separated vs an array). bind is different: it doesn't call the function — it returns a new function with this permanently locked, to be called whenever you're ready.
greet.call(user, "Hi") — runs greet RIGHT NOW, with this set to user, args comma-separated.
bind doesn't call the function — fn.bind(obj) returns a new function; you still have to call that. Forgetting this is a common source of "why didn't this run" bugs.const click = button.onClick; click() loses this (it becomes undefined in strict mode). button.onClick.bind(button) is the direct fix — arrow functions and class fields solve the same problem differently, by never having their own this to lose.this argument entirely — they don't have their own this to override, so passing one has no effect."Implement your own bind" is a real, common exercise — it forces you to prove you understand that bind both fixes this and returns a new callable function, not just one of the two.