bind实现

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值