Function.prototype.MyCall = function(context = globalThis,...args){
context = context || globalThis
const __key__ = Symbol()
context[__key__] = this
const result = context[__key__](...args)
delete context[__key__]
return result
}
function greet(message) {
console.log(`${message}, ${this.name}!`);
}
const person = {
name: 'Alice'
};
const name = 'Bob';
// 使用 MyCall 方法调用 greet 函数,并将 person 对象作为上下文
greet.MyCall(person, 'Hello'); // 输出:Hello, Alice!
// 使用 MyCall 方法调用 greet 函数,并将全局对象作为上下文
greet.MyCall(null, 'Hello'); // 输出:Hello, undefined!
// 使用 MyCall 方法调用 greet 函数,并将 name 变量作为上下文
greet.MyCall({ name }, 'Hello'); // 输出:Hello, Bob!