javascript - 有人可以在 javascript 示例中解释这个 "passing arguments"吗?

标签 javascript function arguments call apply

我正在通读 Javascript Garden ,我正在尝试围绕以下示例进行思考:

Passing Arguments

The following is the recommended way of passing arguments from one function to another.

 function foo() {
     bar.apply(null, arguments);
 }
 function bar(a, b, c) {
     // do stuff here
 }

Another trick is to use both call and apply together to create fast, unbound wrappers.

 function Foo() {}

 Foo.prototype.method = function(a, b, c) {
     console.log(this, a, b, c);
 };

 // Create an unbound version of "method" 
 // It takes the parameters: this, arg1, arg2...argN
 Foo.method = function() {

     // Result: Foo.prototype.method.call(this, arg1, arg2... argN)
     Function.call.apply(Foo.prototype.method, arguments);
 };

我想弄清楚两件事:

1) 什么是“未绑定(bind)包装器”?

2) 从 .call 到 .apply 的链接如何工作和/或使代码更快?

最佳答案

"1) What exactly is an "unbound wrapper"?"

Unbound wrapper 只是一个函数,它通过传递所需的 this 值和参数来调用另一个函数。

"2) How does the chaining from .call to .apply work and/or make the code faster?"

.call.apply() 比必须在 arguments 上执行 .slice() 来分隔 更快>this 来自实际的参数。

否则它需要这样做,这会比较慢:

Foo.method = function(ths) {

    Foo.prototype.method.apply(ths, Array.prototype.slice.call(arguments, 1));
};

关于javascript - 有人可以在 javascript 示例中解释这个 "passing arguments"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201518/

相关文章:

c - 数组到c中的参数

javascript - jQuery - 从 JSON 中提取数据

javascript - 条件关闭标签 ReactJS

Javascript:从iframe调用父函数

javascript - 使用 for 循环增量打印数组项

命令行参数 argv 和 argc

JavaScript:提交后在表单下显示元素

javascript - 谷歌应用程序脚本 : how to copy array of objects to range?

function - Vala 中的通用函数

c - execl 中 C 程序的负参数被检测为选项