Function.prototype.myCall = function (context = window, ...args) {
if (this === Function.prototype) {
return undefined; // 用于防止 Function.prototype.myCall() 直接调用
}
context = context || window;
const fn = Symbol();
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
}
const obj = {
name: 'kalen',
age: 18
}
function callMe() {
console.log('===')
console.log(this.name)
console.log(arguments)
}
function callMe2() {
console.log('------')
console.log(this.age)
console.log(arguments)
}
console.log('参考链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call')
callMe()
callMe.myCall(obj, 1, 2, 3)
callMe2.myCall(obj, 4, 5, 6)
callMe.call('call', 7, 8, 9)
// 函数调用函数,this.name会返回函数名
console