【问题标题】:Javascript: argument unpacking in function.prototype.bind()? [duplicate]Javascript:function.prototype.bind() 中的参数解包? [复制]
【发布时间】:2016-02-06 02:32:38
【问题描述】:

The closest I've seen is this, but it doesn't really help me since I need to bind some parameters for later use with setInterval.

更具体地说:

[in] var d = function(l, m) {
       console.log(l);
       console.log(m);
     }
[in] d.apply(window, [1,2])
[out] 1
[out] 2
[out-return-value] undefined
[in] d.bind(window, [1,2])()
[out] [1, 2]
[out] undefined
[out-return-value] undefined

可以看出,数组是用.apply()解包的,但不是.bind()。有没有办法用.bind()解包参数?

【问题讨论】:

  • 好像我之前回答过这样一个问题:P

标签: javascript parameter-passing argument-unpacking


【解决方案1】:

.bind 只是另一个函数。如果您想使用参数数组调用它,请使用 .apply 调用它:

var bound = d.bind.apply(d, [window, 1, 2]);
// If the `this` value is known, but the arguments is an array, concat:
// var bound = d.bind.apply(d, [window].concat(args))

【讨论】:

    【解决方案2】:

    试试这个。

    Function.prototype.bindArray(ctx, array) {
      if (array && array.length && array.pop && array.length > 0) {
        var v = array.pop();
        return this.bindArray(ctx, array).bind(ctx, v);
      }
      else return this;
    };
    

    它将迭代地绑定array中的每个值。

    像这样使用它:

    var d = function(l, m) {
      console.log(l);
      console.log(m);
    };
    var c = d.bindArray(null, [1,2]);
    c(); // 1 2
    

    另见下面@felix 的回答。这甚至很酷。

    【讨论】:

    • 我真的很喜欢这个。非常优雅 - 不错!
    • 问题:因为我认为我找到了一个无需迭代的解决方案,这是否也有效,或者如果没有,为什么?:` Function.prototype.bindArray(thisArg, array) {` `array.unshift (thisArg);` ` return this.bind.apply(this, array);` ` }`
    • 这似乎过于复杂(对于任务而言)并创建了不必要的中间函数对象。
    • @13steinj 是的,它有效。这个答案其实很酷。
    猜你喜欢
    • 2013-06-08
    • 1970-01-01
    • 2012-09-28
    • 2020-04-20
    • 2015-12-09
    • 2015-12-10
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多