简易模拟JS的Function对象的call和apply方法


对 call 方法的简易模拟

 1 Function.prototype._call = function(ctx) {
 2     // 将函数自身设置为 ctx 对象的属性
 3     // 非严格模式:
 4     //  - null 或 undefined 的this会自动指向全局对象
 5     //  - 基本类型的this会指向原始值的包装对象
 6     ctx = ctx !== null && ctx !== undefined ? Object(ctx) : window;
 7     ctx.fn = this;
 8 
 9     //// 执行该函数
10     const fnArgs = Array.from(arguments).slice(1);
11     const result = ctx.fn(...fnArgs);
12 
13     // 删除该对象上的函数属性
14     delete ctx.fn;
15 
16     return result;
17 };

对 apply 方法的简易模拟

 1 Function.prototype._apply = function(ctx, args) {
 2     ctx = ctx !== null && ctx !== undefined ? Object(ctx) : window;
 3     ctx.fn = this;
 4 
 5     let result;
 6 
 7     if (Array.isArray(args)) {
 8         result = ctx.fn(...args);
 9     } else {
10         result = ctx.fn();
11     }
12 
13     delete ctx.fn;
14 
15     return result;
16 };