- 都是改变this指向
- 三者第一个参数都是this要指向的对象,如果没有第一个参数或者参数为null或undefined,则默认指向window
- 都可以传参:call可以传入多个字符串,apply是一个数组,call和apply都是一次传入,而bind可以多次传入
- bind是返回绑定之后的函数,而call和apply是绑定即执行
Function .prototype.myCall = function (ctx = window, ...args) {
ctx.fn = this
const result = ctx.fn(...args)
delete ctx.fn
return result
}
// 使用demo
const obj1 = {
num: 1,
sum(a, b) {
console.log(this)
return this.num + a + b
}
}
const obj2 = {
num: 10
}
console.log(obj1.sum.call(obj2, 2, 3)) // 15
console.log(obj1.sum.myCall(obj2, 2, 3)) //15
Function.prototype.myApply = function (ctx = window, args) {
console.log('args', args)
ctx.fn = this
const result = ctx.fn(...agrs)
delete ctx.fn
return result
}
// 使用demo
console.log(obj1.sum.myApply(obj2, [2, 3])) // 15
Function.prototype.myBind = function (ctx = window, ...initargs) {
return (...args) => {
ctx.fn = this
const result = ctx.fn(...initargs, ... args)
delete ctx.fn
return result
}
}
// demo
console.log(obj1.sum.myBind(obj2, 2)(3)) // 15
网友评论