[javascript] EcmaScript 6 spread

來源:互聯網
上載者:User

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

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.