前端開發不得不知的ES6十大新特性

gyfeng1003發表於2019-05-02

es6排名前十的最佳特性列表

  1. 預設引數 in es6
  2. 模板文字 in es6
  3. 多行字串 in es6
  4. 解構賦值 in es6
  5. 增強的物件文字 in es6
  6. 箭頭函式 in es6
  7. Promise in es6
  8. 塊作用域構造Let and Const
  9. Classes 類 in es6
  10. Modules 模組 in es6

1.Default Parameters(預設引數) in ES6

還記得我們以前(ES5)不得不通過下面方式來定義預設引數:

var link = function (height, color, url) {
  var height = height || 50;
  var color = color || 'red';
  var url = url || 'http://azat.co';
    ...
}
複製程式碼

一切工作都是正常的,直到引數值是0後,就有問題了,因為在JavaScript中,0表示false 但在ES6,我們可以直接把預設值放在函式申明裡:

var link = function(height = 50, color = 'red', url = 'http://azat.co') {
  ...
}
複製程式碼

2.Template Literals(模板物件) in ES6

在其它語言中,使用模板和插入值是在字串裡面輸出變數的一種方式。 因此,在ES5,我們可以這樣組合一個字串:

var name = 'Your name is ' + first + ' ' + last + '.';
var url = 'http://localhost:3000/api/messages/' + id;
複製程式碼

幸運的是,在ES6中,我們可以使用新的語法$ {NAME},並把它放在反引號裡:

var name = `Your name is ${first} ${last}. `;
var url = `http://localhost:3000/api/messages/${id}`;
複製程式碼

3.Multi-line Strings (多行字串)in ES6

ES6的多行字串是一個非常實用的功能。 在ES5中,我們不得不使用以下方法來表示多行字串:

var roadPoem = 'Then took the other, as just as fair,nt'
  + 'And having perhaps the better claimnt'
  + 'Because it was grassy and wanted wear,nt'
  + 'Though as for that the passing therent'
  + 'Had worn them really about the same,nt';
    
var fourAgreements = 'You have the right to be you.n
  You can only be you when you do your best.';
複製程式碼

然而在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,`;
    
var fourAgreements = `You have the right to be you.
  You can only be you when you do your best.`;
複製程式碼

4.Destructuring Assignment (解構賦值)in ES6

解構可能是一個比較難以掌握的概念。先從一個簡單的賦值講起,其中house 和 mouse是key,同時house 和mouse也是一個變數,在ES5中是這樣:

// data has properties house and mouse
var data = $('body').data();
var house = data.house,
var mouse = data.mouse;
複製程式碼

在ES6,我們可以使用這些語句代替上面的ES5程式碼:

// we'll get house and mouse variables
var { house, mouse } = $('body').data();
複製程式碼

這個同樣也適用於陣列,非常讚的用法:

var [col1, col2]  = $('.column');
var [line1, line2, line3, , line5] = file.split('n');
複製程式碼

5. 增強的物件字面量

物件字面量已得到了增強。現在我們可以更容易地:

  • 定義具有相同名稱的變數賦值欄位
  • 定義函式
  • 定義動態屬性
const color = 'red'
const point = {
  x: 5,
  y: 10,
  color,
  toString() {
    return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color
  },
  [ 'prop_' + 42 ]: 42
}

console.log('The point is ' + point)
console.log('The dynamic property is ' + point.prop_42)
The point is X=5, Y=10, color=red 
The dynamic property is 42 
複製程式碼

6.Arrow Functions in(箭頭函式) ES6

例如,下面的程式碼用ES5就不是很優雅:

var _this = this;
$('.btn').click(function(event) {
  _this.sendData();
});
複製程式碼

在ES6中就不需要用 _this = this:

$('.btn').click((event) => {
  this.sendData();
});
複製程式碼

7. Promises in ES6

下面是一個簡單的用setTimeout()實現的非同步延遲載入函式:

setTimeout(function() {
  console.log('Yay!');
}, 1000);
複製程式碼

在ES6中,我們可以用promise重寫:

var wait1000 =  new Promise(function(resolve, reject) {
  setTimeout(resolve, 1000);
}).then(function() {
  console.log('Yay!');
});
複製程式碼

到目前為止,程式碼的行數從三行增加到五行,並沒有任何明顯的好處。確實,如果我們有更多的巢狀邏輯在setTimeout()回撥函式中,我們將發現更多好處:

setTimeout(function(){
  console.log('Yay!');
  setTimeout(function(){
    console.log('Wheeyee!');
  }, 1000);
}, 1000);
複製程式碼

在ES6中我們可以用promises重寫:

var wait1000 =  ()=> new Promise((resolve, reject)=> {
  setTimeout(resolve, 1000);
});
wait1000()
  .then(function() {
    console.log('Yay!')
    return wait1000()
  })
  .then(function() {
    console.log('Wheeyee!')
  });
複製程式碼

8.(塊作用域和構造let和const)

const用於定義常量。 let用於定義變數。但是JavaScript中不是已經有變數了嗎? 是的,這很正確,但用var宣告的變數具有函式作用域,並會被提升到頂部。 這意味著在宣告之前就可以使用這個變數。 let變數和常量具有塊作用域(用{}包圍),在宣告之前不能被使用。

9. Classes (類)in ES6

用ES5寫一個類,有很多種方法,這裡就先不說了。現在就來看看如何用ES6寫一個類吧。ES6沒有用函式, 而是使用原型實現類。我們建立一個類baseModel ,並且在這個類裡定義了一個constructor 和一個 getName()方法:

class baseModel {  
  constructor(options, data) { // class constructor
    this.name = 'Base';  
    this.url = 'http://azat.co/api';  
    this.data = data;  
    this.options = options;  
   }  

    getName() { // class method  
        console.log(`Class name: ${this.name}`);  
    }  
}  
複製程式碼

10. Modules (模組)in ES6

在ES6 Module出現之前,模組化一直是前端開發者討論的重點,面對日益增長的需求和程式碼,需要一種方案來將臃腫的程式碼拆分成一個個小模組,從而推出了AMD,CMD和CommonJs這3種模組化方案,前者用在瀏覽器端,後面2種用在服務端,直到ES6 Module出現 ES6 Module使用import關鍵字匯入模組,export關鍵字匯出模組,它還有以下特點:

  • ES6 Module是靜態的,也就是說它是在編譯階段執行、編譯階段就能確定模組的依賴關係,以及輸入和輸出的變數
  • ES6 Module支援使用export {<變數>}匯出具名的介面,或者export default匯出匿名的介面

相關文章