-
-
Save bernar83/79b94a359eea5c0a78bb012b95a35dd8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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