ES6
1. Default Parameters
更快速給定 function 參數預設值
code:javascript
var link = function (
height = 50,
color = "red",
) {
// ...
};
${val}
code:javascript
var name = Your name is ${first} ${last}.;
允許指派多行文字
code:javascript
var name = `first line
second line`;
允許嵌入 tag
code:javascript
function print(text) {
console.log(text);
}
const text = 'Hello world!';
// Hello world!
print${text}
3. Multi-line Strings
允許使用 \ 接受多行字串指派
backticks
code:javascript
var name = 'first line \n \
second line';
4. Destructing Assignment
code:javascript
console.log(a); // 1
console.log(b); // 2
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
5. Object Literals
code:javascript
function getCar(make, model, value) {
return {
make, // same as make: make
model, // same as model: model
value, // same as value: value
depreciate() {
this.value -= 2500;
}
};
}
let car = getCar('Kia', 'Sorento', 40000);
從原本的指向呼叫者改為指向其所屬物件
code:javascript
(param1, param2, ..., paramN) => { statements }
(param1, param2, ..., paramN) => expression
// 等於 : => { return expression; }
// 只有一個參數時, 括號才能不加:
(singleParam) => { statements }
singleParam => { statements }
// 若無參數, 就一定要加括號:
() => { statements }
code:javascript
var wait1000 = () =>
new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
});
wait1000()
.then(function () {
console.log("Yay!");
return wait1000();
})
.then(function () {
console.log("Wheeyee!");
});
作用域從之前 var 的函式變成了離此變數最近的 {} 區塊範圍內
let 不可重覆宣告
重複宣告則執行時會吐出錯誤
const 宣告時即須初始化,並且不可修改
9. Classes
透過 prototype 和 function 實作出類 inheritance 結構的 class
code:javascript
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ' roars.);
}
}
10. Module
code:javascript
// Export
export var port = 3000;
export function getAccounts(url) {
// ...
}
// Import
import { port, getAccounts } from "module";
console.log(port);
Map
{ 鍵 (key) : 值 (value) }
關心鍵與值的對應關係
code:javascript
let mapTable = new Map();
// Add
mapTable.set("string", "string value");
mapTable.set({}, { obj: 1 });
mapTable.set(
function () {},
function () {
console.log("function");
}
);
mapTable.set(1, 100);
// Get
mapTable.get("string");
// Has
mapTable.has({});
// Iterator
// returns for keys
mapTable.keys();
// returns for values
mapTable.values();
// returns for key, value, used by default in for...in mapTable.entries();
// Delete
mapTable.delete(1);
// Delete All
mapTable.clear();
// Length
mapTable.size;
// To Array
Set
{value1, value2}
關心不重覆值的獨立元素
code:javascript
// ES6 Set
// Add
setTable.add(6);
// Has
setTable.has(1);
// Iterator
setTable.entries();
setTable.keys();
setTable.values();
// Delete
setTable.delete(1);
// Delete All
setTable.clear();
// Length
setTable.size;
// To Array
Array.from(setTable);