【问题标题】:Can someone explain this "passing arguments" in javascript example?有人可以在javascript示例中解释这个“传递参数”吗?
【发布时间】:2014-04-07 17:35:50
【问题描述】:

我正在阅读Javascript Garden,并试图围绕以下示例进行思考:

传递参数

以下是将参数从一个函数传递到另一个函数的推荐方法。

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

另一个技巧是同时使用 call 和 apply 来创建快速、未绑定的包装器。

 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) 究竟什么是“未绑定包装器”?

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

【问题讨论】:

  • 其实他想做Foo.method = Function.call.bind(Foo.prototype.method)

标签: javascript function arguments call apply


【解决方案1】:

我觉得代码应该是这样的:

function Foo() {}

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

Foo.method = function() {

 //Notice this line:
 Function.apply.call(Foo.prototype.method, this, arguments);
};

然后

Foo.method(1,2,3) => function Foo() {} 1 2 3

其他例子:

Function.apply.call(Array,this,[1,2]) => [1, 2]
Function.call.apply(Array,this,[1,2]) => [window]
Function.call.call(Array,this,[1,2])  => [[1, 2]]

【讨论】:

    【解决方案2】:

    究竟什么是“未绑定包装器”?

    一个函数,它不能在 一个实例上调用,而是 个实例作为它的参数。它不绑定到原型/不需要绑定到实例。示例:

    var x = new Foo;
    // instead of
    x.method(1, 2, 3);
    // you now call
    Foo.method(x, 1, 2, 3);
    

    这样做的好处是您可以传递函数而无需关心其this 上下文。

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

    它并没有真正让任何东西“更快”。它甚至无法与任何“较慢”的解决方案相比。

    关于它的工作原理,请查看重复的问题What's the meaning to chain call and apply together?

    【讨论】:

      【解决方案3】:

      "1) 究竟什么是“未绑定包装器”?"

      未绑定的包装器只是一个函数,它通过传递所需的this 值和参数来调用另一个函数。

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

      .call.apply() 比必须在 arguments 上执行 .slice() 以将 this 与实际参数分开更快。

      否则就需要这样做,速度较慢:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 2014-11-20
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-16
        相关资源
        最近更新 更多