Skip to content

Instantly share code, notes, and snippets.

@raynerpupo
Created April 17, 2018 03:21
Show Gist options
  • Save raynerpupo/c63d07fd41a281bdaef637d2cfbb5c59 to your computer and use it in GitHub Desktop.
Save raynerpupo/c63d07fd41a281bdaef637d2cfbb5c59 to your computer and use it in GitHub Desktop.

Call apply and bind

Call and Apply

The call and apply functions are similar, they expect a the contex (this) and the parameter to call the function, the only difference is that apply accepts the function parameters in an array.

const calculate = function(x, y) {
  return this.operation(x, y);
}

const multiply = {
  operation: function (x, y) { return x * y };
};

With call:

console.log(calculate.call(multiply, 4, 5)); // => 20

With apply:

console.log(calculate.apply(multiply, [4, 5])); // => 20

Bind

Creates a new function that is already bound to an object so at the moment we call the bounded function we don't need to especify the context:

const mult = calculate.bind(multiply);

console.log(mult(4, 5)); // => 20

Why

All the three allows us to change the context where a function is being called, this could be helpful if we want to use frunctions from another contex like the multiply one, there we have a property called operation that doesn't exist at the moment we called console.log.

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