JavaScript之apply模擬實現javascript
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;i < arr.length; i++) { args.push('arr['+i+']') } result = eval('context.fn('+args+')') } delete context.fn return result }
ES6實現java
Function.prototype.apply2 = function(context,arr){ context = context || window context.fn = this let result if(!arr){ result = context.fn() }else{ let args = [] for(let i=0; i<arr.length; i++) { args.push(arr[i]) } result = context.fn(...args) } delete context.fn return result }