- 都是改變this指向
- 三者第一個參數(shù)都是this要指向的對象腹侣,如果沒有第一個參數(shù)或者參數(shù)為null或undefined,則默認指向window
- 都可以傳參:call可以傳入多個字符串呆细,apply是一個數(shù)組翰意,call和apply都是一次傳入,而bind可以多次傳入
- bind是返回綁定之后的函數(shù)搅幅,而call和apply是綁定即執(zhí)行
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) {
ctx.fn = this
const result = ctx.fn(...(args || []))
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(... args,...initargs)
delete ctx.fn
return result
}
}
// demo
console.log(obj1.sum.myBind(obj2, 2)(3)) // 15
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者