首页 > 移动平台 > 详细

ES6 spread operator 实现Function.prototype.apply

时间:2016-01-25 18:59:55      阅读:241      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!