题目 实现Function.prototype.call 描述 Function.prototype.call可以用来很方便的修改函数的
this
。
你能实现一个myCall
来模拟Function.prototype.call
吗?
根据最新的 ECMAScript spec,thisArg
不会被类型转换,在 Strict Mode下也不会被更改为window。
你的代码需要遵从上述逻辑,实现非strict mode的情况。
Function.prototype.call/apply/bind
和 Reflect.apply 可以了解,但请不要在这里使用。
答案
Function.prototype.mycall = function (thisArg, ...args) {
//获取调用的函数
const target = this;
const flag = Symbol();
//undefined || null 应赋值为globalWindow,其它类型应尝试使用Object(thisArg);
// thisArg = Object(thisArg || globalThis); 0 和 ""也会被改成window
if(thisArg === null || thisArg === undefined){
thisArg = globalThis;
}else{
thisArg = Object(thisArg);
}
//利用this特性:对于普通函数来说,谁调用this就指向谁。
thisArg[flag] = target;
const res = thisArg[flag](...args);
//删除flag属性。
delete thisArg[flag];
return res;
}