mediumJS ES5#53

Function.prototype.bind

Prompt

Given an object with a greet method, use .bind() to create boundGreet — a function that always uses that object as this, even when detached from the object or attached to another one.

Solution

var person = {
  name: 'Alice',
  greet: function() { return 'Hi, ' + this.name }
}
var boundGreet = person.greet.bind(person)
Mentor's take

This exists because this in a regular function is resolved at the call site, not where the function was defined. var fn = person.greet; fn() loses the receiver — this becomes undefined in strict mode (or the global object in sloppy mode), and this.name blows up or reads a global. Every callback API — timers, event handlers, array iteration — invokes your function detached, so this failure mode is everywhere.

.bind(person) returns a new function whose this is permanently fixed. The tests here prove the guarantee is absolute: calling it detached still works, and even attaching it to a different object as a method can't re-point it — an explicit .call/.apply can't either. Bind wins every future this resolution, which is exactly what you want for a callback and exactly why it's called "hard binding."

Two senior details: bind also supports partial application (fn.bind(null, arg1) pre-fills arguments), and the returned function is a distinct identity — binding in a render loop creates a new function each time, which is why React codebases bind once in a constructor or use class fields instead.

Red flag: "I'd just use an arrow function" with no mechanism. Fine as a fix, but the question probes whether you know arrows don't bind this — they never had their own, they capture lexically. Different mechanism, and interviewers check you can name both.

Say it: "this is decided at the call site, so passing a method as a callback loses its receiver — bind returns a new function with the receiver hard-wired, immune to any later call site."