What is the difference between call and apply?

前端 未结 24 1660
太阳男子
太阳男子 2020-11-21 07:12

What is the difference between using call and apply to invoke a function?

var func = function() {
  alert(\'hello!\');
};
         


        
24条回答
  •  情书的邮戳
    2020-11-21 07:52

    The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."

    See MDN's documentation on apply and call.

    Pseudo syntax:

    theFunction.apply(valueForThis, arrayOfArgs)

    theFunction.call(valueForThis, arg1, arg2, ...)

    There is also, as of ES6, the possibility to spread the array for use with the call function, you can see the compatibilities here.

    Sample code:

    function theFunction(name, profession) {
        console.log("My name is " + name + " and I am a " + profession +".");
    }
    theFunction("John", "fireman");
    theFunction.apply(undefined, ["Susan", "school teacher"]);
    theFunction.call(undefined, "Claude", "mathematician");
    theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

提交回复
热议问题