ES6 spread operator 实现Function.prototype.apply

之前出于好奇想自己实现apply的功能(不使用call,bind),一写才发现用eval无法实现,除非传入的参数全是字符串。

今天突然看到这个ES6新特性spread opertor,发现有戏了

Function.prototype.apply2 = function(obj, arg) {
  var t = typeof obj == 'object' && !!obj ? obj : window,
    res;
  t.__func__ = this;
  if(arg) {
    if(!Array.isArray(arg)) throw 'arg is not array';
    res = t.__func__(...arg);  //es6
  } else {
    res = t.__func__();
  }
  delete t.__func__;
  return res;
};

 

用eval是可以实现的

Function.prototype.call2 = function(obj) {
  var t = typeof obj == 'object' && !!obj ? obj : window,
    args = Array.prototype.slice.call(arguments, 1),
    len = args.length,
    res;
  t.__func__ = this;
  if(len) {
    res = eval('t.__func__('+args.map(function(arg, index) {return ',args['+index+']'}).join('').substr(1)+')');
  } else {
    res = t.__func__();
  }
  delete t.__func__;
  return res;
};

 

posted @ 2016-01-25 17:54  coIorZ  阅读(205)  评论(0编辑  收藏  举报