引自冴羽
大佬的代码,可以说比较完整了。
Function.prototype.call = function (context) {
let context = context || window;
let fn = Symbol('fn');
context.fn = this;
let args = [];
for(let i = 1, len = arguments.length; i < len; i ) {
args.push('arguments[' i ']');
}
let result = eval('context.fn(' args ')');
delete context.fn
return result;
}
不过我认为换成 ES6 的语法会更精炼一些:
代码语言:javascript复制Function.prototype.call = function (context, ...args) {
let context = context || window;
let fn = new Symbol('fn');
context.fn = this;
let result = eval('context.fn(...args)');
delete context.fn
return result;
}
类似的,有apply的对应实现:
代码语言:javascript复制Function.prototype.apply = function (context, args) {
let context = context || window;
context.fn = this;
let result = eval('context.fn(...args)');
delete context.fn
return result;
}