Created
November 1, 2013 18:41
-
-
Save mateuszkocz/7269897 to your computer and use it in GitHub Desktop.
Bind context to call function. Source: https://variadic.me/posts/2013-10-22-bind-call-and-apply-in-javascript.html
This file contains hidden or 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
var slice = Array.prototype.slice; | |
// slice is now "unbound". As Array.prototype.slice usually | |
// acts on the context it is given, or "this", it will | |
// no longer work. | |
slice(0, 1); // => TypeError: can't convert undefined to object | |
slice([1,2,3], 0, 1); // => TypeError: ... | |
// But if we recall apply and call, they let us supply a context. | |
slice.call([1,2,3], 0, 1); // => [1] | |
// Apply works like call, but takes arguments as an array. | |
slice.apply([1,2,3], [0,1]); // => [1] | |
// It sure gets old using .call though. What if we bind it? | |
// That's right! Let's bind "call" to slice. Yes. | |
slice = Function.prototype.call.bind(Array.prototype.slice); | |
// Now slice uses the first argument as context. | |
slice([1,2,3], 0, 1); // => [1] | |
// | |
// Pretty cool huh? But I got one last thing for you. | |
// | |
// Let's put "bind" itself through the same process | |
// we did "slice". | |
var bind = Function.prototype.call.bind(Function.prototype.bind); | |
// Wrap your mind around that. Think about it. | |
// What does it do? We are flipping "call", | |
// returning a function that takes a function | |
// and a context and returning a fully bound function. | |
// Bringing back our original example. | |
var context = { foo: "bar" }; | |
function returnFoo () { | |
return this.foo; | |
} | |
// And using our new amazing "bind". | |
var amazing = bind(returnFoo, context); | |
amazing(); // => bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment