apply
// thisArg指向传入的对象
// function内this隐式绑定:this指向调用myApply的函数
Function.prototype._apply = function(thisArg,args){
// 非严格模式下,传入null或undefined thisArg指向window
// 其他转化为包装类型
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)
thisArg.fn = this
// 调用函数后的返回值
const res = thisArg.fn(...args)
delete thisArg.fn
return res
}
call
// thisArg指向传入的对象
// function内this隐式绑定:this指向调用myApply的函数
Function.prototype._call = function(thisArg,...args){
// 非严格模式下,传入null或undefined thisArg指向window
// 其他转化为包装类型
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)
thisArg.fn = this
// 调用函数后的返回值
const res = thisArg.fn(...args)
delete thisArg.fn
return res
}
bind
返回值:返回一个原函数的拷贝,并拥有指定的 this
值和初始参数。
// thisArg指向传入的对象
// function内this隐式绑定:this指向调用myApply的函数
Function.prototype._bind = function (thisArg, ...args1) {
// 非严格模式下,传入null或undefined thisArg指向window
// 其他转化为包装类型
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)
thisArg.fn = this
// 返回一个函数
// 该函数接收剩余的参数,参数合并后执行
return (...args2) => {
thisArg.fn(...[...args1, ...args2])
}
}