javascript - call 和 apply 和有什么不一样?

标签 javascript performance function dynamic

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

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

func.apply(); vs func.call();

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

最佳答案

不同的是,apply 允许您使用 arguments 作为数组来调用函数; call 需要明确列出参数。一个有用的助记符是 A 表示 a 射线,C 表示 comma。”

参见 MDN 的文档 applycall .

伪语法:

theFunction.apply(valueForThis, arrayOfArgs)

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

从 ES6 开始,还可以使用 spread call 函数使用的数组,您可以查看兼容性 here .

示例代码:

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

关于javascript - call 和 apply 和有什么不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1986896/

相关文章:

MySQL 查询 - 为什么在这种情况下不使用索引?

performance - Clojure 中的 Takeuchi 数字(性能)

c# - 通过引用传递在 C# 中是如何工作的?

function - 为什么最终结果会有所不同?

javascript - 安排图标和布局

javascript - 在 Vue 中使用 v-for 处理 v-if 的正确方法

javascript - Imacros - 使用 Javascript 循环多个宏特定次数

PHP序列化函数-将序列化后的数据添加到mysql中,然后获取并显示

azure - 如何定位deployment.yaml文件中的特定值?

javascript - 如何从 C# 添加数据到动态添加的下拉列表