我无法理解这个javascript函数是如何工作的

Dav*_*iov 27 javascript logic

我正在阅读bind函数定义,但我无法100%理解编写的代码:

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
                                       ? this 
                                       : oThis || window,
                                     aArgs.concat(Array.prototype.slice.call(arguments)));
            };

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

        return fBound;
    };
}
Run Code Online (Sandbox Code Playgroud)

具体来说,我没有达到目的fNOP,我不明白为什么fBound需要设置原型.我也挂在这个fToBind.apply部分(我无法弄清楚这在这个背景下代表什么).

有人可以解释这里发生了什么吗?

Tik*_*vis 6

好吧,fBound需要设置原型的一个原因是调用bind函数的结果与该函数具有相同的原型.这也是fNop似乎进入的地方 - 它允许你设置fBound原型使用new fNop()而不调用可能有副作用的原始功能.

调用apply允许您this在函数中设置并指定其他参数.由于bind允许您"加入"函数的参数,因此必须将绑定函数时传入的参数和调用它的参数组合在一起.

  • 而不是使用fNop,为什么你不能只说fBound.prototype = this.prototype?我认为这与fNop检查实例的原因有关,这是我无法推理的部分 (3认同)