call 和 apply 和有什么不一样?

问题描述

不同之处在于apply,您可以将函数arguments作为数组调用;call要求明确列出参数。一个有用的助记符是 A代表数组,C代表逗号”。

请参阅 MDN 关于applycall的文档。

伪语法:

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

从 ES6 开始,还可以spread将数组与函数一起使用,您可以在此处call查看兼容性。

示例代码:

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

解决方法

Function.prototype.apply()使用和Function.prototype.call()调用函数有什么区别?

var func = function() {
  alert('hello!');
};
func.apply();` 对比 `func.call();

上述两种方法之间是否存在性能差异?什么时候最好使用callover apply,反之亦然?

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...