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.

avi will reach at 10.


    function sayHi(date,time){
        console.log(`${this.name} will reach on ${date} at ${time}.`);
    }    
        
    const user={name:"avi"};
    
    sayHi.bind(user,["Sunday",10]);