technology-blog
technology-blog copied to clipboard
第 7 题:手写代码,简单实现apply
Function.prototype.apply2 = function(context, arr) {
var context = context || window; //因为传进来的context有可能是null
context.fn = this;
var args = [];
var params = arr || [];
for (var i = 0; i < params.length; i++) {
args.push("params[" + i + "]"); //不这么做的话 字符串的引号会被自动去掉 变成了变量 导致报错
}
args = args.join(",");
var result = eval("context.fn(" + args + ")"); //相当于执行了context.fn(arguments[1], arguments[2]);
delete context.fn;
return result; //因为有可能this函数会有返回值return
}
ES 6版本
Function.prototype.apply2 = function(context, arr) {
let context = context || window; // 因为传进来的context有可能是null
context.fn = this;
arr = arr || [];
const result = context.fn(...arr); // 相当于执行了context.fn(arguments[1], arguments[2]);
delete context.fn;
return result; // 因为有可能this函数会有返回值return
}
参数中带 context ,再用 let 声明一遍会报错的
ES 6版本
Function.prototype.apply2 = function(context, arr) { let context = context || window; // 因为传进来的context有可能是null context.fn = this; arr = arr || []; const result = context.fn(...arr); // 相当于执行了context.fn(arguments[1], arguments[2]); delete context.fn; return result; // 因为有可能this函数会有返回值return }
既然都已经用ES6了,就再彻底点
Function.prototype.myApply = function(context = window, args = []) {
context.fn = this;
const result = context.fn.call(context, ...args);
delete context.fn;
return result;
}