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
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
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
.