ES6、ES7、ES8特性-學習提煉總結(一)

ECMAScript 6.0,簡稱ES6是JavaScript語言的下一代標準,在2015年6月釋出。目的是讓JavaScript語言可以用來編寫複雜的大型應用程式,成為企業級開發語言。
Babel轉碼器
Babel是一個廣泛使用的ES6轉碼器,可以將ES6程式碼轉為ES5程式碼,從而在現有環境執行。
Babel的配置檔案是 .babelrc
,存放在專案的根目錄下。使用Babel的第一步,就是配置這個檔案。
Babel提供 babel-cli
工具,用於命令列轉碼。
babel-cli工具自帶一個 babel-node
命令,提供一個支援ES6的REPL環境。它支援Node的REPL環境的所有功能,而且可以直接執行ES6程式碼。它不用單獨安裝,而是隨babel-cli一起安裝。
$ npm install --save-dev babel-cli
babel-register
模組改寫require命令,為它加上一個鉤子。此後,每當使用require載入.js、.jsx、.es和.es6字尾名的檔案,就會先用Babel進行轉碼。
$ npm install --save-dev babel-register
如果某些程式碼需要呼叫Babel的API進行轉碼,就要使用 babel-core
模組。
$ npm install babel-core --save
Babel預設只轉換新的JavaScript句法(syntax),而不轉換新的API,比如Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise等全域性物件,以及一些定義在全域性物件上的方法(比如Object.assign)都不會轉碼。
ES6在Array物件上新增了Array.from方法。Babel就不會轉碼這個方法。如果想讓這個方法執行,必須使用 babel-polyfill
,為當前環境提供一個墊片。
$ npm install --save babel-polyfill
let和const命令
let和const只在當前塊級作用域下宣告才有效。
{ let a = 10; var b = 1; } a // ReferenceError: a is not define. b // 1 複製程式碼
不存在變數提升
// var 情況 console.log(foo); // undefined var foo = 2; // let 情況 console.log(bar); // 報錯ReferenceError let bar = 2; 複製程式碼
暫時性死區
console.log(bar); // 報錯ReferenceError let bar = 2; 複製程式碼
不允許重複宣告
let a; let a; console.log(a); // 報錯 複製程式碼
const 宣告一個只讀的常量。一旦宣告,常量的值就不能改變。
ES6宣告變數的六種方法:
var、function、let、const、import、class
變數的解構賦值
陣列的解構賦值
let [a, b, c] = [1, 2, 3]; // a = 1; b = 2; c = 3; let [a, b, c = 3] = [1,2]; // a = 1; b = 2; c = 3; 複製程式碼
物件的解構賦值
let { foo, bar } = { foo: "aaa", bar: "bbb" }; 複製程式碼
字串的解構賦值
const [a,b,c,d,e] = 'hello'; 複製程式碼
函式引數的解構賦值
funtion add([x, y]) { return x + y; } add([1,2]);// 3 複製程式碼
用途
- 交換變數的值
let x = 1; let y = 2; [x, y] = [y, x]; 複製程式碼
- 從函式返回多個值
// 返回一個數組 function example() { return [1, 2, 3]; } let [a, b, c] = example(); // 返回一個物件 function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example(); 複製程式碼
- 函式引數的定義
// 引數是一組有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 引數是一組無次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1}); 複製程式碼
- 提取JSON資料
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); 複製程式碼
- 函式引數的預設值
JQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true } = {}) { // do stuff }; 複製程式碼
- 遍歷Map結構
const map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); for (let [key, value] of map) { console.log(key + " is " + value); } // first is hello // second is world // 獲取鍵名 for (let [key] of map) { // ... } // 獲取鍵值 for (let [,value] of map) { // ... } 複製程式碼
參考資料:
ofollow,noindex">caibaojian.com/es6/