ES6、ES7、ES8特性-學習筆記(一)

讓內心永遠保持簡單樂觀發表於2019-03-04

ES6

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
複製程式碼
for (let i = 0; i < 10; i++) {}
console.log(i); // ReferenceError: i is not defined
複製程式碼

for 迴圈計數器,適合用let命令宣告

// var 宣告
var a = [];
for (var i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i);
    }
}
a[0]();  // 10

// let 宣告
var a = [];
for (let i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i);
    }
}
a[0](); // 0
console.log(i);
// ReferenceError: i is not defined

複製程式碼

不存在變數提升 - let命令宣告的變數必須先宣告後賦值,在let命令宣告變數之前,該變數不可用。

// var情況
console.log(foo); // undefined
var foo = 2;
// let情況
console.log(bar); // ReferenceError
let bar = 2;

// y沒有宣告之前,不能賦值給x
function bar(x = y, y = 2) {
    return [x, y];
}
bar(); // error

function bar(x = 2, y = x) {
    return [x, y];
}
bar(); // [2, 2]
複製程式碼

暫時性死區 - 塊級作用域存在let命令,這個區域被所宣告的let繫結

var temp = 1;
if (true) {
    // TDZ開始
    temp = 2; // ReferenceError
    let temp; 
    // TDZ結束
}
複製程式碼

let不允許在相同作用域內,重複宣告同一個變數。

let a; 
let a; 
console.log(a); // 報錯
複製程式碼

const 宣告一個只讀的常量。一旦宣告,常量的值就不能改變。const只能保證所宣告當前變數的地址不變,不能保證指向的資料結構是不是可變的。

// const宣告的基本資料型別不能改變
const a = 1;
a = 2; // error

// const宣告的引用資料型別中的屬性值可被重新賦值
const obj = {};
obj.attr = value;
obj.attr; // value;
複製程式碼

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 [a, [b, c], d] = [1, [2, 3], 4]; // a = 1; b = 2; c = 3; d = 4;
複製程式碼
// 解構不成功為undefined
let [x, y, ...z] = ['a']; // x = 'a'; y = undefined; z = [];
複製程式碼
// 可以設定預設值
let [x, y = 'b'] = ['a', undefined]; // x = 'a'; y = 'b';
複製程式碼
// ES6通過嚴格運算子(===),判斷一個位置是否有值,只有一個陣列成員嚴格等於undefined,預設值才會生效
let [x = 1] = [undefined];  x // 1
let [x = 1] = [null]; x // null
複製程式碼
  • 物件的解構賦值
// 變數名和屬性名一致
let { foo, bar } = { foo: "aaa", bar: "bbb" }; 
<===> 
let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };
foo // aaa
var // bbb
複製程式碼
let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined
複製程式碼
// 如果變數名與屬性名不一致
let { foo: a } = { foo: "aaa", bar: "bbb" };
a // "aaa"

let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'
複製程式碼
// 解構可以用於巢狀結構的物件
let obj = {
    p: [
        'Hello',
        { y: 'World' }
    ]
};
let { p: [ x, { y }] } = obj;
x // 'Hello'
y // 'World'
複製程式碼
const node = {
    loc: {
        start: {
            line: 1,
            column: 5
        }
    }
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // { start: Object }
start // { line: 1, column: 5 }
複製程式碼
  • 字串的解構賦值
const [a,b,c,d,e] = 'hello';
a // 'h'
b // 'e'
c // 'l'
d // 'l'
o // 'o'
複製程式碼
let { length: len } = 'hello';
len // 5
複製程式碼
  • 數值和布林值的解構賦值
// 解構賦值時,如果等號右邊是數值和布林值,則先轉化為物件
let { toString: s } = 123;
s === Number.prototype.toString // true

let { toString: s } = true;
s === Boolean.prototype.toString // true
複製程式碼
  • 函式引數的解構賦值
// 函式的引數可以使用解構賦值
funtion add([x, y]) {
    return x + y;
}
add([1,2]);  // 3
複製程式碼
[[1, 2], [3, 4]].map(([a, b]) => a + b); // [3, 7]
複製程式碼
// 函式move的引數是一個物件,通過對這個物件解構,得到x和y;解構失敗,x和y為預設值
function move({x = 0, y = 0} = {}) {
    return [x, y];
}
<===>
function move({x = 0, y = 0}) {
    return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({});  // [0, 0]
move();  // [0, 0]
複製程式碼
// 為函式引數指定預設值,而不是為變數x和y指定預設值
function move({x, y} = {x: 0, y: 0}) {
    return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({});  // [undefined, undefined]
move();  // [0, 0]
複製程式碼

用途

  • 交換變數的值
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) {
  // ...
}
複製程式碼

參考資料:

caibaojian.com/es6/

阮一峰ECMAScript 6入門

相關文章