首页 > 解决方案 > 为什么不在绑定方法 polyfill 中检查这个 instanceof fBound 呢?

问题描述

这是来自 MDN 的旧版本的bind方法 polyfill:

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;
    };
}

我对this instanceof fNOP这里感到困惑。我知道有时我们可以将 fBound 返回bind方法称为构造函数。像这样:

const fn2 = fn1.bind()
new fn2()

所以我觉得的目的this instanceof fNOP是帮助判断我们如何调用函数return by bindmethod并做一些相对的事情。但是为什么不在this instanceof fBound这里检查呢?如果 fBound 作为构造函数调用,那么this一定是 fBound 的一个实例,对吧?

PS:最新版的bind polyfill已经把this instanceof fNOPcheck变成了fNOP.prototype.isPrototypeOf(this)check,不过我觉得目的是一样的。无论如何,它仍然检查fNOP而不是fBound,我不太明白。

标签: bindpolyfills

解决方案


推荐阅读