bind和apply、call方法一样都是改变调用者的this指向,唯一的区别就是bind()方法不立即执行
下边是源码解析
Function.prototype.binds=function(ctx){
var contex = ctx
if(contex == null) consloe.log(new Error('error'));
else{
var args = [].slice.call(arguments,1)
//或者用es6的方法
//var args = [...arguments].slice(1)
var self =this;
function fn(){}
fn.prototype = this.prototype//继承调用者的原型方法
var bound = function(args){
return self.apply(contex,args || null) //执行this函数
}
bound.prototype = new fn()//bound继承了fn的实例属性与原型属性(this.prototype)
return bound
}
}
大致模拟的就是这样,,有不足望各位大佬指出。