先看一个例子:
showName.call(obj) 等于 obj.fn()
// 把当前执行函数的this指向传入的对象obj,等于在对象obj中调用当前函数
// 创建obj中的假当前函数fn=Symbol(),通过obj[fn] = this将当前函数转给他
// 执行假函数并返回,返回前删除创建的假函数
Function.prototype.myCall = function (obj = window, ...args) {
const fn = Symbol();
obj[fn] = this;
const newFunc = obj[fn](...args);
delete obj[fn];
return newFunc;
}
Function.prototype.myApply = function (target, args) { // 区别就是这里第二个参数直接就是个数组
target = target || window
const symbolKey = Symbol()
target[symbolKey] = this
const res = target[symbolKey](...args) // args本身是个数组,所以我们需要解构后一个个传入函数中
delete target[symbolKey] // 执行完借用的函数后,删除掉,留着过年吗?
return res
}
Function.prototype.myBind = function(obj, ...outArgs) {
const fn = Symbol();
obj[fn] = this;
return function(...innerArgs) {
const res = obj[fn](...outArgs, ...innerArgs);
delete obj[fn];
return res
}
}