Skip to main content

模拟apply

tip

考察this的应用,是对代码基础能力是否扎实的一种体现。

Function.prototype.apply = Function.prototype.apply || function(){
// 只有Function才可以调用apply方法
if(typeof this !== 'function'){
throw new TypeError('must be function');
}

const args = Array.from(arguments); // 将参数列表转换成真正的数组
const bindThis = args.shift() || window; // 第1个参数,是设定this
const fnArgs = args.shift() || []; // 第2个参数,传递给当前的function(因为apply的第2个参数,是数组)

// 如果第2个参数不是数组,则不符合规范
if(!Array.isArray(fnArgs)){
throw new TypeError('args must be array');
}

const fn = Symbol('fn'); // 利用Symbol实现唯一key,不与代码中的key重复
bindThis[fn] = this; // this指向的是当前要调用的Function
const result = bindThis[fn](...fnArgs); // 将当前要执行的Function,挂在绑定的this对象下执行,则Function内部的this指针,指向的是当前的this对象(bindThis)

delete bindThis[fn]; // 执行完成后,作清除操作,避免占用内存

return result;
}