functiongenerateFunctionCode(argsLength) { let res = "return arguments[0][arguments[1]]("; for (let i = 0; i < argsLength; i++) { if (i > 0) { res += ","; } res += "arguments[2][" + i + "]"; } res += ")"; // 相当于 return 'arguments[0][arguments[1]](arguments[2][0], arguments[2][1], arguments[2][2]...)'; return res; }
Function.prototype.applyFn = functionapply(thisArg, argsArray) { // 调用方必须是函数 if (typeofthis !== "function") { thrownewTypeError(this + "is not a function"); } // 非严格模式下,thisArg 如果为 null 或 undefined,就会被替换成全局对象 if (thisArg === null || thisArg === void0) { thisArg = getGlobalObject(); } // 非严格模式下,thisArg 如果为原始值,就会被替换成原始值的的自动包装对象 thisArg = newObject(thisArg); if (argsArray === null || argsArray === void0) { argsArray = []; } if (argsArray !== newObject(argsArray)) { thrownewTypeError("The second parameter must be an array like object."); } const hasOriginVal = thisArg.hasOwnProperty("fn"); const originVal = thisArg["fn"]; thisArg["fn"] = this; const code = generateFunctionCode(argsArray.length); const result = newFunction(code)(thisArg, "fn", argsArray); if (hasOriginVal) { thisArg["fn"] = originVal; } else { delete thisArg["fn"]; } return result; };