旧版本的 bind polyfill 实现中,为什么不检查 this 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 是为了判断调用 bind 之后返回的函数是正常调用还是 new 调用,如果是 new 调用,则 this 就是调用完生成的实例,由于原型链的关系,这个语句会返回 true。但既然是这个目的的话,为什么不直接检查 this insatnceof fBound 呢?这样好像更直接一点。还是说这里两种检查方式都可以,没有区别呢?

阅读 895
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进