【问题标题】:Explain Javascript's Function.prototype.bind browser shim解释 Javascript 的 Function.prototype.bind 浏览器 shim
【发布时间】:2014-12-10 21:38:29
【问题描述】:

我只是想真正理解以下来自 MDN 的代码。它是 Function.prototype.bind 的垫片:

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP && oThis
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

首先,为什么 aArgs 最初会忽略参数列表中的第一个参数?

其次,为什么 fToBind 采用 aArgs 数组并将其余参数连接起来?这不会创建一个 args 1 到 n 与 args 0 到 n 连接的数组吗?

我很困惑!

【问题讨论】:

    标签: javascript this bind partial-application


    【解决方案1】:

    首先,为什么 aArgs 最初会忽略参数列表中的第一个参数?

    因为第一个参数是将 this 设置为 (oThis) 的值。我们不想稍后将它作为参数传递给函数。

    其次,为什么 fToBind 采用 aArgs 数组并将其余参数连接起来?这不会创建一个 args 1 到 n 与 args 0 到 n 连接的数组吗?

    是的。请注意,这些是不同的参数集。 aArgs 指的是传递给.bind() 的参数,而arguments 指的是绑定函数 fBound 的参数。

    我们希望同时传递已传递给.bind 的参数和已传递给绑定函数的参数。 IE。我们想要

    var fBound = f.bind(null, a, b); // aArgs = [a, b];
    fBound(c, d); // arguments = [c, d]
    

    等同于f(a, b, c, d)


    基本上,它会完成所有工作,以便 shim 像 .bind 预期的那样工作。如果您对实现感到困惑,您可能需要花更多时间来更好地理解.bind

    【讨论】:

    • 为什么绑定需要多个参数?我的印象是改变this的上下文?
    • 没关系。我猜你可以绑定任意数量的参数,假设第一个是this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    相关资源
    最近更新 更多