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

后端 未结 22 1919
醉话见心
醉话见心 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:30

    Syntax

    • call(thisArg, arg1, arg2, ...)
    • apply(thisArg, argsArray)
    • bind(thisArg[, arg1[, arg2[, ...]]])

    Here

    • thisArg is the object
    • argArray is an array object
    • arg1, arg2, arg3,... are additional arguments

    function printBye(message1, message2){
        console.log(message1 + " " + this.name + " "+ message2);
    }
    
    var par01 = { name:"John" };
    var msgArray = ["Bye", "Never come again..."];
    
    printBye.call(par01, "Bye", "Never come again...");
    //Bye John Never come again...
    
    printBye.call(par01, msgArray);
    //Bye,Never come again... John undefined
    
    //so call() doesn't work with array and better with comma seperated parameters 
    
    //printBye.apply(par01, "Bye", "Never come again...");//Error
    
    printBye.apply(par01, msgArray);
    //Bye John Never come again...
    
    var func1 = printBye.bind(par01, "Bye", "Never come again...");
    func1();//Bye John Never come again...
    
    var func2 = printBye.bind(par01, msgArray);
    func2();//Bye,Never come again... John undefined
    //so bind() doesn't work with array and better with comma seperated parameters

提交回复
热议问题