问题

使用call和apply调用函数有什么区别?

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

func.apply();

vs

func.call();

两种方法之间是否存在性能差异?什么时候最好使用通过应用程序,反之亦然?



解决方法

不同之处在于 apply 允许您使用 arguments 作为数组调用函数; call 需要明确列出参数.一个有用的助记符是"A for array and C for comma."

请参阅MDN有关应用 call .

伪语法:

theFunction.apply(valueForThis,arrayOfArgs)

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

从ES6起,还有可能 <代码> spread 数组用于调用函数,您可以看到兼容性此处.

示例代码:

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

// Output: 

// My name is John and I am a fireman.
// My name is Susan and I am a school teacher.
// My name is Claude and I am a mathematician.
// My name is Matthew and I am a physicist.



相关问题推荐