卡尼多隨筆

認識自我 • 感受世界 • 創造價值

0%

JavaScript ES6 Cheatsheet

之前學 ES6 時整理的筆記😀

在開始之前

有位網友 Giana 寄信推薦我一款網頁工具:JS & CSS Unminifier

This tool does the job: it unminifies, reformats and reforms JavaScript (and CSS) code, making it readable again. (It’s very user-friendly and free! )

之所以推薦我這個,是因為她在找 unminify 工具的過程當中找到了我這篇文章,她在信中很樂於分享地說:

I’m sure your readers will appreciate it, especially if they’ve struggled like me.

所以說,怎能不分享個呢😎(謝謝 Giana!)


參考自:[ES6] Javascript 開發者必須知道的 10 個新功能

Default Parameters

MDN:
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

1
let person = function(height = 173, weight = 66, college = 'NCTU') { ... };

Template Literals

MDN:
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Multi-line Strings

1
2
3
4
5
6
7
// ES5
let sentence = 'first line\n'
+ 'second line';

// ES6
let sentence = `first line
second line`;

String Interpolation

1
2
3
4
5
// ES5
let sentence = 'My name is ' + first + ' ' + last + '.';

// ES6
let sentence = `My name is ${first} ${last}.`;

Destructuring Assignment

MDN:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

1
2
3
4
5
6
7
let me = { name: 'Tim', college: 'NCTU' };

let moreAboutMe = { me, gender: 'male' };
// { { name: 'Tim', college:'NCTU' }, gender: 'male' }

let moreAboutMe = { ...me, gender: 'male' };
// { name: 'Tim', college:'NCTU' , gender: 'male' }

Array destructuring

1
2
3
4
5
const foo = ['one', 'two', 'three'];
const [red, yellow, green] = foo;
console.log(red); // one
console.log(yellow); // two
console.log(green); // three

Object destructuring

1
2
3
4
const me = { name: 'Tim', college: 'NCTU' };
const { name, college } = me;
console.log(name); // Tim
console.log(college); // NCTU

Object Literals

[筆記] JavaScript ES6 中的物件的擴展(object literal extension)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function makeMachine(name, year, price) {
return {
// name: name,
name,
year,
// 也可以覆蓋掉傳進來的值
price: 810000,

// ⽅法 methods 也能放進來
description: function() {
console.log(`${year} machine ${name} is ${price} dollars`);
},
// 簡寫
description() {
console.log(`${year} machine ${name} is ${price} dollars`);
},

// 允許將表達式 expression 作為屬性名稱,以達到動態賦值的效果(包在[]裡⾯)
[year+'machine']: price,
};
}

let machine = makeMachine('Switch', 2020, 9780);

machine.description();
// 2020 machine Switch is 9780 dollars

console.log(machine.price);
// 810000

Arrow Functions

MDN:
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can’t be used in all situations.

1
2
3
4
5
6
7
8
9
10
11
// 多個參數
(param1, param2, ..., paramN) => { statements };
(param1, param2, ..., paramN) => { return expression; };
(param1, param2, ..., paramN) => expression;

// ⼀個參數
(singleParam) => { statements };
singleParam => { statements };

// 沒有參數
() => { statements };

Promises

Promise 學習筆記 | DEVLOG of andyyou

MDN:
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

建⽴ Promise

Promise 想成是⼀個 object!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
hasEnoughMoney = false;

const pleaseBuyMeSwitch = new Promise((resolve, reject) => {
if (hasEnoughMoney) {
const gift = {
name: 'Switch',
price: 9780,
};
resolve(gift); // 回傳 gift 這個物件
} else {
const reason = new Error('I lost my 20000 dollars at the gym!!!');
reject(reason); // 回傳 reason 這個 Error 物件
}
});

使⽤ Promise

1
2
3
4
5
6
7
8
9
10
11
12
let askJoeman = function() {
pleaseBuyMeSwitch
.then((fulfilled) => {
console.log('I got:');
console.log(fulfilled);
})
.catch((error) => {
console.log(error.message);
})
};

askJoeman();

簡化寫法

若某個 function 沒呼叫 reject

1
2
3
4
5
6
const showoff = function(something) {
return new Promise((resolve, reject) => {
let message = `Hahaha! I got a new ${something}!`;
resolve(message);
});
};

可簡寫成

1
2
3
4
const showoff = function(something) {
let message = `Hahaha! I got a new ${something}!`;
return Promise.resolve(message);
};

ES7 async/await ⾮同步寫法

原本的寫法

1
2
3
4
5
6
7
8
9
10
let askJoeman = function() {
pleaseBuyMeSwitch
.then((fulfilled) => {
console.log('I got:');
console.log(fulfilled);
})
.catch((error) => {
console.log(error.message);
})
};

新寫法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async function askJoeman() {
try {
let something = await pleaseBuyMeSwitch;
let message = await showoff(something.name);
console.log(message);
} catch(error) {
console.log(error.message);
}
}

// await ⼀定要包在 async function 裡⾯才能⽤

(async() => {
await askJoeman();
})()

cleaner and more readable!

Let & Const, Block-Scoped

let 僅在當前的 block 內有效,重複定義時會 throw error。
const 同樣只在當前的 block 內有效,定義時必須 initialize,且不能更改。

Classes

MDN:
Classes are a template for creating objects. They encapsulate data with code to work on that data.

Class Declaration 類別宣告

1
2
3
4
5
6
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

Class Expression 類別敘述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// unnamed
let People = class {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

// named
let People = class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

使用方式

1
let PG = new People('Curry', 32);

Prototype Methods 原型⽅法

可包 getter、setter、method 等等的進到 class 定義裡⾯,詳⾒ MDN

Static methods 靜態⽅法

不需要實體化就可以被呼叫,也無法被已實體化的類別物件呼叫。
經常被⽤來建⽴給應⽤程式使⽤的⼯具函數。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}

static greeting(name, age) {
console.log(`My name is ${name}. I'm ${age} years old now.`);
}
}

let SG = new People('Thompson', 30);

SG.greeting('Thompson', 30);
// Thrown:
// TypeError: SG.greeting is not a function

People.greeting('Green', 30);
// My name is Green. I'm 30 years old now.

⽤ extends 建⽴⼦類別 & ⽤ super 呼叫⽗類別

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Player {
constructor(name) {
this.name = name;
}

introduce() {
// console.log(`I'm ${name}.`); name 前⾯沒加上 this 會報錯
console.log(`I'm ${this.name}.`);
}
}

class Star extends Player {
constructor(name, number, position) {
super(name);
this.number = number;
this.position = position;
}

introduce() {
super.introduce();
console.log(`I wear number ${this.number}. I play ${this.position}!`);
}
}

let star = new Star('Antetokounmpo', 34, 'PF');
star.introduce();
// I'm Antetokounmpo.
// I wear number 34. I play PF!

// 之前幻想字母哥來勇士xD

Module

MDN:
providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed.

Export

MDN:
The export statement is used when creating JavaScript modules to export live bindings to functions, objects, or primitive values from the module so they can be used by other programs with the import statement.

1
2
export password = 'hello';
export function getStatus(id) { ... };

Import

MDN:
The static import statement is used to import read only live bindings which are exported by another module.

1
2
import { password, getStatus } from 'module-name';
console.log(password); // hello

Export Default

可以讓要使⽤ module 的 client,在不知道 module export 了哪些名稱的情況下,能⾃訂名稱取⽤ module 裡⾯定義的東西。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export default {
name: 'Tim',
greeting() {
console.log('Hello!');
},
}

/* ================================================== */

import any-name-you-want-to-take from 'module-name';

console.log(any-name-you-want-to-take.name);
// Tim

any-name-you-want-to-take.greeting();
// Hello!

希望讀完這篇文章的您能夠有所收穫,我們下篇文見啦 😃