--- tags: react, note --- # 第 2 章:ES6 與 NPM ## Variable - const 是不能重新賦值 (re-assign),內容其實是可以更改的。 - var 作用域為 Scope let / const 作用域為 Block - 作用域分為 Scope / Block Scope 分為 Function Scope / Global Scope Block 即為 {} 範圍 ## Functions - 傳統 Function 的 This 是依據執行時的情境 (Context); Arrow Function 的 This 直接指向該 Function 宣告時所處之情境。 (包覆 Arrow Function 之情境) 把 "This" 學得更精一點。 ## Import / Export - import 時,副檔名為 js 的話可以省略 ".js" - 使用 export default,import 時可以直接隨意命名 - 使用 Named Export 時,import 需要先使用 大括號 + 同名 來引用,需要重新命名的話請加上 "as" 關鍵字作串接 ```javascript /*----- Export File -----*/ export const PI = 3.1415; /*----- Import File -----*/ import { PI as P } from 'index.js'; ``` ## Class ```javascript /*----- 標準寫法 -----*/ class Dog extends Animal { constructor() { // 建構式 // Properties this.age = 0; } // Methods bark() { console.log('Woof!'); } } // Instant (實例) const spot = new Dog(); ``` - Property = Class 中的 Variable; Method = Class 中的 Function。 - Constructor 是特殊的 Method,是在 new 時候要執行的程式。 ```javascript /*----- 使用 "babel class-properties" 作轉譯時的寫法 -----*/ class Dog extends Animal { // Properties age = 0; // Methods bark = () => console.log('Woof!'); } // Instant (實例) const spot = new Dog(); ``` ## ES6 其他好用特色 ### 解構賦值 ```javascript /*----- 陣列 -----*/ const point = [1, 2, 3]; /* 1 */ const [x, y, z] = point; // x = 1, y = 2, z = 3 /* 2 */ const [,y] = point; // y = 2 /* 3 */ const [x, ...rest] = point; // x = 1, rest = [2, 3] /*----- 物件 -----*/ const point = { x: 1, y: 2, z: 3 }; /* 1 */ const { x, y, z } = point; // x = 1, y = 2, z = 3 /* 2 */ const { y } = point; // y = 2 /* 3 */ const { y, ...rest } = point; // y = 2, rest = { x: 1, z: 3 } /*----- 共通 -----*/ /* 預設值 "=" */ const { x, y, z, w = 0 } = point; // 如果 point 內沒有該屬性,則 w 預設為零。 /* 重新命名 ":" */ const { x: hi } = point; // hi = 1 /* 預設值 + 重新命名 */ const { x: hi = 0 } = point; // hi = 1 (元物件就存在 x) ``` ### 異步處理 ```javascript // 傳統 callback callSomeAPI(function(result) { console.log(result); }); // Promise callSomeAPI() .then(result => { console.log(result); }); // async / await const start = async () => { const result = await callSomeAPI(); } start(); ``` :::info :bulb: Promise、async/await 再多了解一下 :::