為了保證可讀性,本文采用意譯而非直譯,并且對源代碼進行了大量修改。另外,本文版權歸原作者所有,翻譯僅用于學習。
ES6,正式名稱是ECMAScript2015,但是ES6這個名稱更加簡潔。ES6已經不再是JavaScript最新的標準,但是它已經廣泛用于編程實踐中。如果你還沒用過ES6,現在還不算太晚…
下面是10個ES6最佳特性,排名不分先后:
函數參數默認值 模板字符串 多行字符串 解構賦值 對象屬性簡寫 箭頭函數 Promise Let與Const 類 模塊化 函數參數默認值 不使用ES6為函數的參數設置默認值:
function foo(height, color){ var height = height || 50; var color = color || 'red'; //...}這樣寫一般沒問題,但是,當參數的布爾值為false時,是會出事情的!比如,我們這樣調用foo函數:
foo(0, "", "")
因為0的布爾值為false,這樣height的取值將是50。同理color的取值為‘red'。
使用ES6
function foo(height = 50, color = 'red'){ // ...}模板字符串
不使用ES6
使用+號將變量拼接為字符串:
var name = 'Your name is ' + first + ' ' + last + '.'
使用ES6
將變量放在大括號之中:
var name = `Your name is ${first} ${last}.`ES6的寫法更加簡潔、直觀。
多行字符串
不使用ES6
使用“/n/t”將多行字符串拼接起來:
var roadPoem = 'Then took the other, as just as fair,/n/t' + 'And having perhaps the better claim/n/t' + 'Because it was grassy and wanted wear,/n/t' + 'Though as for that the passing there/n/t' + 'Had worn them really about the same,/n/t'
使用ES6
將多行字符串放在反引號“之間就好了:
var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same,`
解構賦值
不使用ES6
當需要獲取某個對象的屬性值時,需要單獨獲取:
var data = $('body').data(); // data有house和mouse屬性var house = data.house;var mouse = data.mouse;使用ES6
一次性獲取對象的子屬性:
var { house, mouse} = $('body').data()對于數組也是一樣的:
var [col1, col2] = $('.column');對象屬性簡寫
不使用ES6
對象中必須包含屬性和值,顯得非常多余:
var bar = 'bar';var foo = function (){ // ...}var baz = { bar: bar, foo: foo};使用ES6
對象中直接寫變量,非常簡單:
var bar = 'bar';var foo = function (){ // ...}var baz = { bar, foo };
新聞熱點
疑難解答
圖片精選