bind

我们使用 this 容器丢失绑定,使用 bind 可以一次性绑定,并且不会有丢失绑定问题。

第一版本

我们需要返回一个新的函数,新的函数(用来绑定的).

if (!Function.prototype.bind) {
    Function.prototype.bind = function (context, ...args) {
        return (...Nargs) => {
            return this.apply(args, Nargs);
        }
    }
}

第二版本。 不使用 ES6 的。

if (!Function.prototype.bind) {
    Function.prototype.bind = function (context) {
        var aArgs = Array.prototype.slice.call(arguments, 1),
        fBind = this;
        Function.prototype.bind = function () {
            return function () {
                return fBind.apply(aArgs.concat(Array.prototype.slice.call(arguments)));
            }
        }
    }
}

第三版本

绑定函数能够使用 new 操作符创建对象: 像把原函数当成构造器。

提供的 this 会被忽略。

if (!Function.prototype.bind) {
    Function.prototype.bind = function (context) {
        var aArgs = Array.prototype.slice.call(arguments, 1),
        fBind = this,
        fBound = function () {
            return fBind.apply(
                this instanceof fBound ? this : context,
                aArgs.concat(Array.prototype.slice.call(arguments))
            )
        }
        fBound.prototype = this.prototype;
        return fBound;
    }
}

第四版本

上面的存在一个问题,当我们返回函数与bind绑定的函数的原型指到一块区域,会存在一个一改都改的问题,它们应该是两个指向。 可以利用一个函数中转一下。

if (!Function.prototype.bind) {
    Function.prototype.bind = function (context) {
        var aArgs = Array.prototype.slice.call(arguments, 1),
        fBind = this,
        fNop = function () {},
        fBound = function () {
            return fBind.apply(
                this instanceof fBound ? this : context,
                aArgs.concat(Array.prototype.slice.call(arguments))
            )
        }
        fNop.prototype = this.prototype;
        fBound.prototype = new fNop();
        return fBound;
    }
}

最终版本

上面我们利用创建一个函数来使得返回的函数与绑定函数的变为原型的关系,但是我们也多创建了一个中转函数.

我们可以利用 Object.create 直接从一个对象上创建实例。

并且我们需要判断 this 是否为一个 函数。

if (!Function.prototype.bind) {
    Function.prototype.bind = function (context) {
        if (typeof this !== 'function') {
            throw new Error('this is not Function');
        }
        var aArgs = Array.prototype.slice.call(arguments, 1),
        fBind = this,
        fBound = function () {
            return fBind.apply(
                this instanceof fBound ? this : context,
                aArgs.concat(Array.prototype.slice.call(arguments))
            )
        }
        fBound.prototype = Object.create(this.prototype);
        return fBound;
    }
}