call
Function.prototype.myCall = function(thisArg, ...args) {
//判断thisArg(要指向的目标对象)的类型,如果是null或者undefined就返回window,否则用Object包装一下
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
//将调用函数地址复制给目标对象的fn属性
thisArg.fn = this
//通过目标对象去调用fn函数,并返回(这里参数用了数组结构语法,和参数不同,参数是剩余参数语法,将剩余的参数存入数组,就算没有参数也会是空数组)
let result = thisArg.fn(...args)
//删除给目标对象上添加的fn属性
delete thisArg.fn
//返回通过目标对象调用fn函数返回的结果
return result
}
apply
Function.prototype.myApply = function(thisArg, arryArg) {
//判断thisArg(要指向的目标对象)的类型,如果是null或者undefined就返回window,否则用Object包装一下
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
//将调用函数地址复制给目标对象的fn属性
thisArg.fn = this
//定义一个变量来保存调用fn函数的返回值
let result
//如果什么都没传入则直接正常调用
if (!arryArg) {
result = thisArg.fn()
} else {
//参数是一个数组,这里采用数组结构,如果不是一个迭代对象的话会报错
result = thisArg.fn(...arryArg)
}
//删除给目标对象上添加的fn属性
delete thisArg.fn
//返回通过目标对象调用fn函数返回的结果
return result
}
bind
Function.prototype.myBind = function(thisArg, ...arg1) {
//判断thisArg(要指向的目标对象)的类型,如果是null或者undefined就返回window,否则用Object包装一下
thisArg = (thisArg !== null & thisArg !== undefined) ? Object(thisArg) : window
//定义一个that变量保存要调用函数的内存地址
let that = this
//bind函数特殊调用bind函数会返回一个函数
return function(...arg2) {
//给目标对象添加一个fn属性并保存调用函数的地址
thisArg.fn = that
//通过目标对象调用函数,并将返回值存入变量result
let result = thisArg.fn(...[...arg1, ...arg2])
//删除目标对象的fn属性
delete thisArg.fn
//返回这个result返回值
return result
}
}