Function.prototype.myApply = function(context, args) {
// Step 1: 判断调用对象
if (typeof this !== 'function') {
throw new TypeError('Type Error');
}
// Step 2: 获取 this
context = context || window;
// Step 3: 创建一个唯一的属性名
const fnSymbol = Symbol();
context[fnSymbol] = this;
// Step 4: 调用这个方法
const result = args ? context[fnSymbol](...args) : context[fnSymbol]();
// Step 5: 删除我们新创建的方法
delete context[fnSymbol];
return result;
}
// 使用示例
function greet(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
let person = {name: 'John'};
console.log(greet.myApply(person, ['Hello', '!'])); // Output: 'Hello, John!'