Skip to content

Instantly share code, notes, and snippets.

@limianwang
Last active August 29, 2015 14:26
Show Gist options
  • Save limianwang/8c142a81cfc2a9944a2a to your computer and use it in GitHub Desktop.
Save limianwang/8c142a81cfc2a9944a2a to your computer and use it in GitHub Desktop.
Tutorial: Bind Function

In the powerful world of JS, you can do a lot of crazy things with Bind/Apply/Call. Here, I can show a small example so that it can be easily understood.

function test1(a, b, c) {
  console.log(Array.prototype.slice.call(arguments));
  // What will this output?
}

function test2(fn) {
  fn();
  // What if we did fn(10000);
}

function main() {
  test2(test1.bind(null, 1, 2, 3));
}

main();

Because of the wonders of bind, what the function is doing is that it remembers the arguments that it was bound to during initalization stage. So in this case test1.bind() will bind 1, 2, 3 as the arguments to pass when it is called.

So what happens when we did fn(1000)? The answer is simple, JS simply pushes that value to the end of the argument array list, so in fact you would get something like:

// console.log(Array.prototype.slice.call(arguments));
[1, 2, 3, 1000]

Neat?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment