只是简单实现一下功能。思路比较简单主要就是用到了闭包的思想。 call和apply一样都是立即执行的,bind是手动执行的,也就说call和apply返回的是函数执行的结果,bind返回的是一个函数。
Function.prototype.myCall = function(target = window,...arg){
target.fn = this
return target.fn(...arg)
}
Function.prototype.myApply = function(target = window,arg){
target.fn = this
return target.fn(arg)
}
Function.prototype.myBind=function(obj,...arg){
var context=this;
var bound=()=> context.apply(obj,arg)
return bound;
}
var obj1 = {
name:'我是obj1',
fun1(...arg){
console.log(this.name,"参数:",arg)
},
}
var obj2 = {
name : '我是obj2'
}
obj1.fun1.myCall(obj2,1,2,3,4)
obj1.fun1.myApply(obj2,[1,2,3,4])
obj1.fun1.myBind(obj2,1,2,3,4)()