[javascript] EcmaScript 6 spread

最近小弟在实现一个Class方法时,为了保证在不用new关键字的情况下也能产生实力,又要传递参数。所以费了很大力气,但是代码还是不够优美。今晚终于找到答案,解决方案就是es6的 spread

 

具体案例请见https://github.com/Neverland/Class/blob/master/script/class.js

 

es6 官方对spred的解释是

  • Replace an array or array-like actual parameter value with its elements as positional parameters
  • Let new compose with a this-free form of apply
  • Remove (some day, and in similar future methods) automagic (and half-the-time wrong) array flattening, e.g. in Array.prototype.concat
     

按照在下理解就是

1.把类数组或者数组这类实际参数值替换成多个位置参数

2.在使用new时不必考虑使用apply的情况

3.移除自动化数组扁平化

 

语法:

 ...非常简单 三个点

 

具体案例:

1.如果同时使用new 和apply会导致语法错误 // new Elements.apply(document.getElementsByTagName('div'));

 

new Elements(...document.getElementsByTagName('div'));

 

2. 结构赋值,可以区段拆解

var [a,...b]=[1,2,3,4];
a //1;
b //[2,3,4]

 

3.调用函数时,直接拆解类数组或数组参数

var a=[1,2,3,4];

如果调用某个函数时,把数组a拆解成4个值传入,以前要借助apply

add.apply(this,a);

现在

add(...a);

  

posted @ 2012-08-07 01:30  小玉西瓜  阅读(324)  评论(1编辑  收藏  举报