手写实现call、apply和bind是面试中常考的手写题,这里提供几个手写方案。
call
Function.prototype.myCall(thisArg, ...args){
//1. 获取调用call的函数对象
let fn = this
//2. 获取要绑定的对象
thisArg = thisArg !== null && thisArg !== undefined ? Object(thisArg) : window
//3. 将绑定的对象上加上fn
thisArg.fn = fn
//4. 执行并获取结果
return thisArg.fn(...args)
}
apply
Function.prototype.myApply(thisArg, argArray){
let fn = this
thisArg = thisArg !== null && thisArg !== undefined ? Object(thisArg) : window
thisArg.fn = fn
return thisArg.fn(...(argArray || [])) //如果没有值的话赋值空数组,否则用不了。
}
bind
Function.prototype.myBind(thisArg, ...args1){
let fn = this
function proxyFn(...args2){
thisArg = thisArg !== null && thisArg !== undefined ? Object(thisArg) : window
thisArg.fn = fn
let result = thisArg.fn(...[...args1,...args2])
delete thisArg.fn
return result
}
return proxyFn
}