進入 Vue.js 前的 ES6 必備知識


Posted by hoyi-23 on 2021-08-13

1.varletconst

這三者在JavaScript皆是用來宣告變數,最大的差別是他們的作用域(scope)。
var: 作用範圍是function
letconst: 作用範圍是block/{}

letconst 的差別

const所宣告的變數還無法被重新賦值 (re-assign)。


2. ES Module 與 import、export

這兩篇是關於 Vue的元件。
app.component 和 export default ?
多個 Component 元件如何組在一起?
我們可以把每個JavaScript檔案當作是一個獨立的模組,在使用import(匯入)、export(匯出)。


3. 箭頭函式與 this

下面這篇文章有簡單說明 this 的指向
this 與 call() / apply() / bind(),apply(),bind()/)

在JavaScript中,this的指向有五個重點:

  1. this 一般來說,不在乎位置,要看它是如何被呼叫的。
  2. 透過call() / apply() / bind() 指定 this。
  3. 箭頭函式中的this,指向是全域(就是它外面的this),而且不能透過bind()指定。
  4. DOM 的 this 會綁定
  5. Simple Call(立即函式、CallBack Function、Clousure)的this,指向是全域。

箭頭函式

在ES6出現的箭頭函式/)


4. 字串模板 (Template literals)

過去我們組合JS變數與HTML模板時,大多是透過 + 字串結合的方式,或透過陣列來新增字串,最後再用[].join("")的方式接起來。
到了ES6,就可以簡單的用字串模板啦!

const name = 'Bibo'
const newString = ` Hi, I am ${name}`

5.解構賦值 (Destructuring assignment)

ES6的解構賦值語法可以把陣列或物件內的資料解開變成獨立變數。

物件

const person = {
    name: 'Ted',
    age: 38,
    family:{
        dad: 'Bob',
        mom: 'June'
    }
}

const {name,age,family} = person;

consol.log(name); //'Ted'

陣列

const num = [1,2,3,4,5];
const [x,y] = num;
console.log(x) //1

... 運算子

文章參考 " ... " 在JavaScript中的意思?

展開運算子(spread operator)

展開運算子 通常用在 陣列 或是 函式的參數。

將陣列內的東西展開

const data = ['010','020','030'];
const arr = ['000',...data];
console.log(arr) // ['000',010','020','030']

用在函式參數

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

其餘運算子(rest operator)

將陣列內的東西分離

console.log(arr) // ['000',010','020','030']

const [a,b,...others] = arr //解構賦值
console.log(a) //'000'
console.log(b) //'010'
console.log(others) //'020','030'

Promise 物件,async 與 await

為了解決同步與非同步的問題,ES6出現了 promise物件。
關於 JavaScript Promises
關於 JavaScript Async Await


#ES6







Related Posts

Poetry

Poetry

Day 03:  GraphQL and GiHub GrapQL - Operations, Variables, and Mutations

Day 03: GraphQL and GiHub GrapQL - Operations, Variables, and Mutations

Day 25-Pandas & U.S States Game [Hard]

Day 25-Pandas & U.S States Game [Hard]


Comments