call函数
结合网上大多数手写call函数的案例,我发现直接将函数挂载到call函数指定的对象里的话,实际调用的时候会导致先打印了this再删除挂载的函数,通过研究call函数的实际底层,将其挂载到指定对象的隐式原型上可以解决
Function.prototype.call1 = function () {
// 提取参数
const args = [...arguments]
// 如果参数没传就定义为window
const _this = args.shift() || window
// 防止覆盖原有的属性
const fn = Symbol('fn')
// 将调用 call1 的函数保存到 指定的 this 对象下面的隐式原型的方法里
_this.__proto__[fn] = this const result = _this[fn](...args)
// 删除挂载的函数
delete _this.__proto__[fn]
return result
}
function fn1(a, b, c) {
console.log(this);
console.log(a, b, c);
}
fn1.call1({ a: 100 }, 10, 20, 30)