Function.prototype.myCall = function(context, ...args) {
// 将函数调用的上下文修改为传入的 context 对象
const newContext = context || window;
// 将当前函数(调用 myCall 的函数)存储在 fn 中
newContext.fn = this;
// 在新的上下文中调用函数,并传递参数 args
const result = newContext.fn(...args);
// 删除临时保存的函数
delete newContext.fn;
// 返回函数的执行结果
return result;
};
// 使用
const o = { name: 'cc' };
function fn() {
console.log(this.name);
}
fn.myCall(o); // cc