簡易模擬JS的Function物件的call和apply方法
阿新 • • 發佈:2021-11-30
對 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 //// 執行該函式 10const 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 };