Function.prototype.call = function (...arg) {
// 1 判断context是否为object,如果是object就代表可能是Object 或者 null,如果不是就赋值一个空对象
let context = arg[0];
if (typeof context === "object") {
context = context || window; // context 如果是null就会赋值为window
} else {
context = Object.create(null);
}
// 2 在context下挂载一个函数,函数所在的key随机生成,防止context上已有同名key
let fn = new Date().getTime() + "" + Math.random(); // 用时间戳+随机数拼接成一个随机字符串作为一个新的key
context[fn] = this;
// 3 newCall如果还有其他的参数传入也要考虑用到
let args = arg.slice(1);
// 4 重点在这里,执行context[fn]这个函数
let result = context[fn](...args); //
delete context[fn]; // 用完后从context上删除这个函数
// 5 返回结果
return result;
};
function aa(a, b) {
console.log(this.x, a, b);
}
let obj = { x: 100 };
aa.call(obj, 10, 100);
网友评论