Skip to content

Instantly share code, notes, and snippets.

@bernar83
Created October 26, 2017 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bernar83/79b94a359eea5c0a78bb012b95a35dd8 to your computer and use it in GitHub Desktop.
Save bernar83/79b94a359eea5c0a78bb012b95a35dd8 to your computer and use it in GitHub Desktop.
function sayName() {
console.log(this.name);
}
var obj = {
name: 'Adrian'
};
var sayObjName = function hardBind() {
sayName().call(obj);
}
sayObjName(); // "Adrian"
setTimeout(sayObjName, 200); // "Adrian"
sayObjName.call(window); // "Adrian"
```
In the example we explicitly bind `sayName()` to `obj` but implemented hard binding. In this case, hard binding happens when we invoke `sayObjName()` and at the same time it invokes `hardBind()` and will now forcibly bind `sayName()` with `obj`. So no matter what we do with `sayObjName()` at a later time, `sayName()` applies to `obj`.
In fact, hard binding is so common there is already a built-in method called `Function.prototype.bind()`. The `bind()` method is used like before but with different syntax:
```js
function sayName() {
console.log(this.name);
}
var obj = {
name: "Adrian"
};
var sayObjName = sayName.bind(obj);
sayObjName(); // "Adrian"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment