JavaScript call, bind and apply functions

call, bind and apply are methods of functions in javascript. As JavaScript Functions are First Class Objects, so functions cal have properties and methods. length, name are functions properties (readonly properties) and call, bind and applyfunctions method.

As we have already discussed function properties in JavaScript Functions, we will only focus of Functions methods.


call

functions call method calls the function with given this value and arguments are provided individually. this will refer to the object passed in arguments. Other arguments are provided after first argument will pass to function.

call method with this

greetings from avi.


    function sayHi(){
        console.log(`greetings from ${this.name}.`);
    }    
    
    const user={name:"avi"};

    sayHi.call(user);

call method with this and other argument

avi will reach at 10.


    function sayHi(time){
        console.log(`${this.name} will reach at ${time}.`);
    }    
    
    const user={name:"avi"};

    sayHi.call(user,10);

bind

bind methods return a new function instead of calling it immediately.

greetings from avi.


    function sayHi(){
        console.log(`greetings from ${this.name}.`);
    }    
        
    const user={name:"avi"};
    
    let greets=sayHi.bind(user);
    greets();

apply

apply methods works almost same like call, except the second parameter is an array whose elements will be passes to function as arguments. The first parameter is object and second an array.

swift (2011) has lxi, vxi, zxi variants.


function sayHi(x,y,z){
console.log(`${this.name} (${this.year}) has ${x}, ${y}, ${z} variants.`);
}    
        
const car={name:"swift",year:2011};
const variants=["lxi","vxi","zxi"];
    
sayHi.apply(car,variants);

In ES6, use Spread Operator to pass arguments from an Array.