- — — — — — Bind vs Call vs Apply — — — — -

Everything in JavaScript is objects, including String and Functions. Function is a piece of code where data can be passed to operate and it can optionally return data. The data is passed explicitly. A method is a piece of code that is associated with a object.

There are certain methods of the function object and lets look into the Bind, Call and Apply methods.

Bind is a method which returns a function allowing you to pass an array and n number of arguments.
It runs the function in the context of the first argument (most probably an object).

var person1 = {firstName: ‘Lebron’, lastName: ‘James’};
var person2 = {firstName: ‘Kobe’, lastName: ‘Bryant’};

function say() {
console.log(‘Hello ‘ + this.firstName + ‘ ‘ + this.lastName);
}

var sayHelloJames = say.bind(person1);
var sayHelloKobe = say.bind(person2);

sayHelloJon(); // Hello Lebron James
sayHelloKelly(); // Hello Kobe Bryant

Bind can be used for currying functions. We can also use for events like onClick where we don’t know when they will be fired but the
element or context will be known.

Call method also takes the first argument to be the context and it accepts several other arguments. The subsequent arguments are passed
to the function as arguments.

var person1 = {firstName: ‘Lebron’, lastName: ‘James’};
var person2 = {firstName: ‘Kobe’, lastName: ‘Bryant’};

function say(greeting) {
console.log(greeting + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName);
}

say.call(person1, ‘Hello’); // Hello Lebron James
say.call(person2, ‘Hello’); // Hello Kobe Bryant

The limitations of call becomes apparent when you don’t the number of arguments that the function needs.

Apply method solves the above limitation by accepting the arguments in the form of array. So an array is passed as a second argument.

var person1 = {firstName: ‘Lebron’, lastName: ‘James’};
var person2 = {firstName: ‘Kobe’, lastName: ‘Bryant’};

function say(greeting) {
console.log(greeting + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName);
}

say.apply(person1, [‘Hello’]); // Hello Lebron James
say.apply(person2, [‘Hello’]); // Hello Kobe Bryant

Bind is a bit different considering the other two and provides opportunities for passing the function parameters. There maybe situations
where the context is available but the arguments are available later. Bind also preserves the context of this for future execution.
Bind is used mainly for adding events like element.addEventListener(‘click’, this.onClick.bind(this), false);

A naive implementation of bind would be like:

Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
Apply uses Arrays, Call you have to Count the number of arguments.

Array.prototype.slice.call(arguments) — This is a popular method to convert arguments to array

Thanks for reading.
If you enjoyed this article, feel free to hit that clap button 👏 to help others find it.