最近小弟在實現一個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);