作用:借用某个对象的方法同时调用执行。【修改this指向同时执行】
call与apply唯一区别在于参数不同 ; 理解了call实现后就直接上代码
代码实现
Function.prototype._apply = function (obj, arr) {
obj = obj ? Object(obj) : window;
obj.fn = this;
var result;
if (!arr) {
result = obj.fn();
} else {
var args = [];
// 注意这里的i从0开始
for (var i = 0, len = arr.length; i < len; i++) {
args.push("arr[" + i + "]");
};
result = eval("obj.fn(" + args + ")"); // 执行fn
};
delete obj.fn; //删除fn
return result;
};
用ES6实现,更简洁。使用拓展运算符处理参数这里
// ES6 apply
Function.prototype._apply= function (obj, arr) {
obj = obj ? Object(obj) : window;
obj.fn = this;
let result;
if (!arr) {
result = obj.fn();
} else {
result = obj.fn(...arr);
};
delete obj.fn
return result;
};