我正在通读 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/