Javascript call() & apply() vs bind()?

后端 未结 22 1929
醉话见心
醉话见心 2020-11-22 02:42

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way

22条回答
  •  别跟我提以往
    2020-11-22 03:42

    The main concept behind all this methods is Function burrowing.

    Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places. It is accomplished through the use of . call() , . apply() , or . bind() , all of which exist to explicitly set this on the method we are borrowing

    1. Call invokes the function immediately and allows you to pass in arguments one by one
    2. Apply invokes the function immediately and allows you to pass in arguments as an array.
    3. Bind returns a new function, and you can invoke/call it anytime you want by invoking a function.

    Below is an example of all this methods

    let name =  {
        firstname : "Arham",
        lastname : "Chowdhury",
    }
    printFullName =  function(hometown,company){
        console.log(this.firstname + " " + this.lastname +", " + hometown + ", " + company)
    }
    

    CALL

    the first argument e.g name inside call method is always a reference to (this) variable and latter will be function variable

    printFullName.call(name,"Mumbai","Taufa");     //Arham Chowdhury, Mumbai, Taufa
    

    APPLY

    apply method is same as the call method the only diff is that, the function arguments are passed in Array list

    printFullName.apply(name, ["Mumbai","Taufa"]);     //Arham Chowdhury, Mumbai, Taufa
    

    BIND

    bind method is same as call except that ,the bind returns a function that can be used later by invoking it (does'nt call it immediately)

    let printMyNAme = printFullName.bind(name,"Mumbai","Taufa");
    
    printMyNAme();      //Arham Chowdhury, Mumbai, Taufa
    

    printMyNAme() is the function which invokes the function

    below is the link for jsfiddle

    https://codepen.io/Arham11/pen/vYNqExp

提交回复
热议问题