javascript - 解释 Javascript 的 Function.prototype.bind 浏览器 shim

标签 javascript this bind partial-application

我只是想真正理解以下来自 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 连接的数组吗?

我很困惑!

最佳答案

First off, why is aArgs initially ignoring the first argument in the arguments list?

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

Secondly, why is fToBind taking the aArgs array and concatenating the rest of the arguments after? Wouldn't this create an array with args 1 to n concatenated with args 0 to n?

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

我们想要传递已传递给 .bind 的参数和已传递给绑定(bind)函数的参数。 IE。我们想要

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

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

<小时/>

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

关于javascript - 解释 Javascript 的 Function.prototype.bind 浏览器 shim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27411310/

相关文章:

javascript - 使用 image.complete 查找图像是否缓存在 chrome 上?

javascript每3秒设置一次间隔时间,前6秒,然后连续5秒,直到我收到答案

javascript - 检查点是否在多边形内

javascript - (this).attr() 在 jquery.noConflict() 之后停止工作

winapi - 为什么我不能绑定(bind)到 winproc?

javascript - 面向对象与 JavaScript

c++ - "cannot convert ' 这个从 'const hand' 到 'hand &' 的指针是什么意思? (C++)

c++ - 无法重载对 *this 的引用

javascript - Jquery 无法读取 null 错误的属性

javascript - 当 parent 的 HTML 更改时,不会触发 child 的事件