Function.prototype.myApply = function (context = window, args) {
if (this === Function.prototype) {
return undefined; // 用于防止 Function.prototype.myCall() 直接调用
}
context = context || window;
const fn = Symbol();
context[fn] = this;
// let result;
// if(Array.isArray(args)){
// result = context[fn](...args);
// } else {
// result = context[fn]();
// }
const result = context[fn](...args);
delete context[fn];
return result;
}
const obj = {
name: 'kalen',
age: 18
}
function applyMe() {
console.log('===')
console.log(this.name)
console.log(arguments)
}
function applyMe2() {
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')
applyMe()
applyMe.myApply(obj, [1, 2, 3])
applyMe2.myApply(obj, [4, 5, 6])
applyMe.call('call', 7, 8, 9)
// 函数调用函数,this.name会返回函数名
console