码迷,mamicode.com
首页 > 移动开发 > 详细

ES6 spread operator 实现Function.prototype.apply

时间:2016-01-25 19:01:10      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

之前出于好奇想自己实现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;
};

 

ES6 spread operator 实现Function.prototype.apply

标签:

原文地址:http://www.cnblogs.com/coiorz/p/5158143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!