Chapter XXI · The `this` Keyword
bind
The `bind` method returns a brand new function with `this` permanently locked to a specified target object.
01 How It Works
Think of permanently locking a tool fixture into a dedicated custom workbench slot.
Unlike `call` or `apply`, `bind` does not execute the function immediately; it creates a reusable bound copy for later invocation.
example.js
const module = {
x: 42,
getX: function() { return this.x; }
};
const unboundGetX = module.getX;
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); // 42
1. Target a function reference.
2. Call `.bind(contextObj)` to lock the `this` context.
3. Invoke the returned bound function later.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
const user = { name: "Charlie" };
function logName() { console.log(this.name); }
const boundLog = logName.bind(user);
boundLog(); // "Charlie"
Key Takeaway
Use `bind` when you need a reusable function copy with a permanently locked `this` context.