const myCall = function(thisArg, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Error');
}
thisArg = thisArg || window; // 如果没有提供 thisArg,则默认为全局对象
// 使用Symbol创建唯一的属性名,防止属性名冲突
const symbol = Symbol();
thisArg[symbol] = this; // 将当前函数绑定到thisArg上
console.log(this)
// 使用ES6的spread语法来传递参数
const res = args.length ? thisArg[symbol](...args) : thisArg[symbol]();
// 调用后删除创建的属性,防止污染thisArg
delete thisArg[symbol];
return res;
};
// 将myCall方法添加到Function.prototype上
Function.prototype.myCall = myCall;
function concat(a, b) {
return a + b;
}
const obj1 = { x: 10 };
console.log(concat.myCall(obj1, 'Hello, ', 'World!')); // Hello, World!