- call
1.把this增加到context this指向調(diào)用的方法
2.第0個(gè)傳入的是指向的對(duì)象煤傍,這里只需要調(diào)用方法傳入的形參
3.把截取的參數(shù)傳給執(zhí)行回調(diào)函數(shù)
4.刪除context上增加的fn方法
Function.prototype.myCall = function (context = window) {
context.Fn = this
const args = [...arguments].splice(1)
const res = context.Fn(...args)
delete context.fn
return res
}
- apply 跟call類似盖文,前者傳多個(gè)參數(shù),后者傳入數(shù)組
Function.prototype.myApply = function (context = window) {
context.Fn = this
const args = [...arguments[1]] //傳入的數(shù)組拿出來
const res = context.Fn(...args)
delete context.fn
return res
}
- bind 返回一個(gè)函數(shù)
1.保存this指向的方法
2.把傳入的參數(shù)截取出來
3.返回一個(gè)函數(shù)蚯姆,在把call引入到里面五续,返回出來
Function.prototype.myBind = function (context = window) {
const _this = this
const args = [...arguments].splice(1)
return function (...args2) {
//...[...args, ...args2] 可能存在多次調(diào)用,所以把兩者傳入的參數(shù)合二為一
return _this.call(context, ...[...args, ...args2])
}
}