Function.prototype.myCall = function(context) { if (typeofthis !== "function") { thrownewError(`${this} is not a function.`); } if (typeof context != "object") { thrownewError("Arguments error"); }
var args = []; var result; context = context || window; // 如果本身存在 fn 属性,先保存,使用完毕,后恢复 if ("fn"in context && context.hasOwnProperty("fn")) { var fn = context.fn; var fnFlag = true; }
// 1. 将函数设为对象的属性 context.fn = this;
for (var i = 1, l = arguments.length; i < l; i++) { // args = ["arguments[1]", "arguments[2]"] args.push("arguments[" + i + "]"); } // 2. 执行该函数 result = eval("context.fn(" + args + ")");
Function.prototype.myapply = function(context, arr) { if (typeofthis !== "function") { thrownewError(`${this} is not a function.`); } context = context || window; context.fn = this;
let result; if (!arr) { result = context.fn(); } else { let args = []; for (var i = 0, l = arr.length; i < l; i++) { args.push("arr[" + i + "]"); } result = eval("context.fn(" + args + ")"); } delete context.fn; return result; };
ES6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Function.prototype.myapply = function(context) { if (typeofthis !== "function") { thrownewError(`${this} is not a function.`); } context = context || window; context.fn = this;
const args = arguments[1]; let result;
if (!args) { result = context.fn(); } else { result = context.fn(...args); }