首页 > 解决方案 > 试图理解绑定方法的底层代码

问题描述

我正在查看绑定实现的代码片段,并且正在努力理解它是如何工作的:

// Credit to Douglas Crockford for this bind method
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;
    };
}

按顺序,我有以下问题:

  1. 我如何看待thisin: if (typeof this !== "function")?我的理解是,通常this是指拥有/包含被调用函数的对象。在这种情况下,是那个对象:A)。函数原型?或 B)。包含应用绑定的函数的对象(即,如果我们有,someFunc.bind(someObj)那么this上面是否指的是持有的对象someFunc?如果是,如果该对象包含除 之外的许多其他方法someFunc怎么办?如果是这样,我们如何处理this对象除了我们感兴趣的功能之外还包含许多无关功能的可能性,someFunc?)

  2. var aArgs = Array.prototype.slice.call (arguments, 1). . . 为什么将1作为参数传递给调用方法?

  3. fToBind = this我有与上面#1相同的问题。具体指的 什么?this

  4. 的目的是(this instanceof fNOP && oThis)什么?我(当然不正确)对此的解读是,“真实”的情况是何时this是包含空函数且 oThis 不为 NULL 的对象的实例?如果是这种情况,为什么会导致this,如果不是这种情况,为什么会导致 的“虚假”情况oThis

  5. 中的连接发生了什么:aArgs.concat (Array.prototype.slice.call (arguments))?这里不会arguments引用 fBound 的参数吗?如果是这样,为什么我们要将这些与bind方法的参数连接起来(这是我假设aArgs代表的)?

  6. 服务于什么目的fNOP.prototype = this.prototype; fBound.prototype = new fNOP ()?毕竟,在下一行,函数返回fBound. 返回是否fBound意味着我们真的在返回fBound.prototype(即fNOP()is的一个新实例this.prototype)?如果是这样,那不会忽略/“覆盖”:

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

    但如果不是,那么fBound.prototype = new fNOP ()分配的目的是什么?

标签: javascript

解决方案


推荐阅读