js实现call、apply、bind方法
实现的过程可以对比原有的call()、apply()、bind()来进行参考
call
//由于是函数上的方法所以在所有函数上添加
Function.prototype.myCall(thisArg,...args){
//获取要执行的函数
let fn = this;
// 用于对thisArg进行对象转换,防止非对象类型的转换
// Object() 可以将值转换为各类型对象
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
// 调用需要执行的函数 -- 也可以执行使用fn.call(thisArg)
thisArg.fn = fn;
let result = thisArg.fn(...args)
delete thisArg.fn //这部分是因为js实现会有一个函数指向属性,但不影响
return result;
}
apply
Function.prototype.myApply(thisArg,argArray){
// 获取到真实需要调用的函数
let fn = this;
// 绑定this
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window
argArray = argArray ? argArray || [];
// 将函数放到thisArg中进行调用
thisArg.fn = fn;
let result = thisArg.fn(...argArray);
delete thisArg.fn
return result;
}
bind
Function.prototype.myBind = function(thisArg, ...argArray) {
// 获取到真实需要调用的函数
let fn = this
// 绑定this
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window
// 由于bind需要用变量接收,并且接收的函数还可以继续传值,值由后添加所以返回一个函数
function proxyFn(...args) {
// 将函数放到thisArg中进行调用
thisArg.fn = fn
// 特殊: 对两个传入的参数进行合并
let finalArgs = [...argArray, ...args]
let result = thisArg.fn(...finalArgs)
delete thisArg.fn
return result
}
return proxyFn
}