#68: Binding an already-bound function again
Topic: this · Difficulty: ★★★
function greet() { return this.name; }
const a = { name: 'A' };
const b = { name: 'B' };
const boundA = greet.bind(a);
const boundAB = boundA.bind(b);
console.log(boundAB());Output
A
Why
bind() returns a brand new 'exotic' function object with its this permanently locked to the object passed in — that lock cannot be changed by call, apply, or another bind. boundA is permanently tied to a. Calling boundA.bind(b) does not rebind boundA; it creates yet another wrapper, boundAB, whose job is to call boundA with some this, but boundA ignores whatever this it's given and always uses a. So boundAB() still resolves this.name to 'A', not 'B'. Only the FIRST bind on a function ever has any effect on its this.