bind的实现

Function.prototype._bind = function(){
    var self = this   //原函数
    var context = [].shift.call(arguments)  //this上下文 调用时重定向的this
    var args = [].slice.call(arguments)  //参数变成数组传入apply
    return function(){                     //返回一个函数(bind特性)
        self.apply(context, args.concat([].slice.call(arguments)))   //将 bind 的其余参数和调用bind后返回的函数在执行的过程中接收的参数进行拼接,作为一个数组传入apply的第二个参数中去
    }
}
[].shift.call相当于 Array.prototype.shift.call

 

使用:

function func(x){
    console.log(x, this.y)
}
func._bind({y: 'bar'}, 'foo')()

 

call、apply都会立即调用,bind是返回一个函数,需要使用时调用

posted @ 2021-02-22 17:32  Jennyishere  阅读(133)  评论(0)    收藏  举报