var args = [] for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]) }
所以模拟call的基本框架就是
1 2 3 4 5 6 7 8 9
Function.prototype.call2 = function (context) { context.fn = this var args = [] for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]) } context.fn(...args) delete context.fn }
Function.prototype.call2 = function (context) { var context = context || window context.fn = this var args = [] for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]) } var result = context.fn(...args) delete context.fn return result }
apply
apply的区别就是参数的问题,修改的完全体如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Function.prototype.apply2 = function (context, arr) { var context = context || window context.fn = this var result if (!arr) { result = context.fn() } else { var args = [] for (var i = 0, len = arr.length; i < len; i++) { args.push(arr[i]) } result = context.fn(...args) } delete context.fn return result }