实现 bind 函数

Function.prototype.binding = function () {
    let self = this;
    let context = [].shift.call(arguments);
    let args = [].slice.call(arguments);
    console.log('Function binding args', args);

    return function () {
        self.apply(context, [].concat.call(args, [].slice.call(arguments)))
    }
};

let obj = {
    a: 'a'
};

function f(b, c, d) {
    console.log(this.a, b, c, d)
}

f.binding(obj, 'b', 'c', 'd')('e');
f.binding(obj, 'b', 'c')('d', 'e');
f.binding(obj, 'b')('c', 'd', 'e');
f.binding(obj)('b', 'c', 'd', 'e');
输出:

Function binding args [ 'b', 'c', 'd' ]
a b c d
Function binding args [ 'b', 'c' ]
a b c d
Function binding args [ 'b' ]
a b c d
Function binding args []
a b c d

Process finished with exit code 0
从输出可以看出 args 是 f.binding 里除了第一个参数剩下所有的参数,而 [].slice.call(arguments) 是 f.binding 后第二个括号里的参数, args 的 this 是 Function.prototype.binding,[].slice.call(arguments) 的 this 是 f.binding(obj)()。

转载于:https://my.oschina.net/jack088/blog/3102218

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您介绍JS中bind函数实现方法。 在JS中,bind函数是用来改变函数内部this的指向的,它会返回一个新的函数,这个新函数的this指向是我们指定的对象。 以下是一个简单的bind函数实现示例: ```javascript Function.prototype.myBind = function(context) { if (typeof this !== 'function') { throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var self = this; var args = Array.prototype.slice.call(arguments, 1); var fNOP = function() {}; var fBound = function() { var bindArgs = Array.prototype.slice.call(arguments); return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs)); } fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; ``` 在这个函数中,我们首先判断this是否为函数类型,如果不是,就抛出一个 TypeError,确保我们绑定的是一个函数。然后,我们保存this的引用,将传入的参数保存在args变量中,创建一个fNOP函数,最后返回一个新函数fBound。 在fBound函数内部,我们使用apply方法来调用原函数,并且将指定的this和参数传递给它。这里需要注意的是,如果我们使用new关键字来创建fBound函数的实例,那么this指向的就是这个实例对象,否则this指向的就是我们指定的context对象。 最后,我们使用原型链来继承原函数,并将fBound函数的原型指向fNOP的实例,这样我们就可以在fBound函数中访问原函数的prototype属性了。 希望这个简单的bind函数实现可以帮助到您。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值