ES13中五個(gè)最具變革性的JavaScript特性
ES13包含了許多有價(jià)值的特性,徹底改變了我們編寫JavaScript的方式。
從異步升級(jí)到數(shù)組語(yǔ)法糖等等,讓我們來看看這些特性,看看你是否錯(cuò)過了其中一些。
1. 頂級(jí)await
在ES13之前,我們永遠(yuǎn)不能在全局作用域中使用await。
? 之前:
// X 語(yǔ)法錯(cuò)誤:await 只在異步函數(shù)中有效
await setTimeoutAsync(3000);
function setTimeoutAsync(timeout) {
return new Promise((resolve) => {
setTimeout(() => {
resolve('codingbeautydev.com');
}, timeout);
});
}
我們總是必須將其放在async函數(shù)中或創(chuàng)建一個(gè)async IIFE(立即執(zhí)行函數(shù)表達(dá)式):
// 異步立即執(zhí)行函數(shù)
(async () => {
await setTimeoutAsync(3000);
})();
// 類似 C++
async function main() {
await setTimeoutAsync(3000);
}
? ES13之后:
// ? 等待超時(shí) - 沒有拋出錯(cuò)誤
await setTimeoutAsync(3000);
function setTimeoutAsync(timeout) {
return new Promise((resolve) => {
setTimeout(() => {
resolve('codingbeautydev.com');
}, timeout);
});
}
2. 類聲明升級(jí)
(1)類字段聲明
在ES13之前,我們只能在構(gòu)造函數(shù)中聲明類字段: 與許多其他語(yǔ)言不同,我們不能在類的最外層作用域中聲明或定義它們。
? 之前:
? 現(xiàn)在有了ES13: 就像在TypeScript中一樣:
(2)私有方法和字段
在ES13之前,創(chuàng)建私有方法是不可能的。 我們還必須使用丑陋的下劃線hack來表示私有性 — 但那只是一個(gè)指示。
? 之前:
class Person {
_firstName = 'Tari';
_lastName = 'Ibaba';
get name() {
return `${this._firstName} ${this._lastName}`;
}
}
const person = new Person();
console.log(person.name); // Tari Ibaba
// 我們?nèi)匀豢梢栽L問私有成員!
console.log(person._firstName); // Tari
console.log(person._lastName); // Ibaba
// 它們也可以被修改!
person._firstName = 'Lionel';
person._lastName = 'Messi';
console.log(person.name); // Lionel Messi
? ES13之后:
我們可以通過在字段前加上井號(hào)(#
)來為類添加私有字段和成員:
如果你試圖從類外部訪問它,你會(huì)得到一個(gè)語(yǔ)法錯(cuò)誤:
class Person {
#firstName = 'Tari';
#lastName = 'Ibaba';
get name() {
return `${this.#firstName} ${this.#lastName}`;
}
}
const person = new Person();
console.log(person.name);
// 語(yǔ)法錯(cuò)誤:私有字段 '#firstName' 必須在封閉的類中聲明
console.log(person.#firstName);
console.log(person.#lastName);
我們可以從錯(cuò)誤消息中看到一些有趣的東西:
編譯器甚至不期望你從類外部嘗試訪問私有字段 — 它假設(shè)你是在嘗試創(chuàng)建一個(gè)。
(3)靜態(tài)類字段和靜態(tài)私有方法
靜態(tài)字段 — 類本身的屬性,而不是任何特定實(shí)例的屬性。
自ES13以來,我們現(xiàn)在可以輕松地為任何類創(chuàng)建它們:
class Person {
static #count = 0;
static eyeCount = 2;
static getCount() {
// 使用 this 訪問同級(jí)靜態(tài)成員
return this.#count;
}
// 實(shí)例成員
constructor() {
// 使用 this.constructor 訪問靜態(tài)成員
this.constructor.#incrementCount();
}
static #incrementCount() {
this.#count++;
}
}
const person1 = new Person();
const person2 = new Person();
console.log(Person.getCount()); // 2
3. 數(shù)組升級(jí):新的at()方法
通常我們會(huì)使用方括號(hào)([])來訪問數(shù)組的第N個(gè)元素。
const arr = ['a', 'b', 'c', 'd'];
console.log(arr[1]); // b
但從末尾訪問第N個(gè)項(xiàng)目一直是一個(gè)痛點(diǎn) -- 我們必須使用arr.length - N進(jìn)行索引:
? ES13之前:
const arr = ['a', 'b', 'c', 'd'];
// 倒數(shù)第1個(gè)元素
console.log(arr[arr.length - 1]); // d
// 倒數(shù)第2個(gè)元素
console.log(arr[arr.length - 2]); // c
幸運(yùn)的是,ES13帶來了一個(gè)新的at()方法,解決了所有這些問題:
const str = 'Coding Beauty';
console.log(str.at(-1)); // y 倒數(shù)第1個(gè)字符
console.log(str.at(-2)); // t 倒數(shù)第2個(gè)字符
4. 靜態(tài)類塊
隨著靜態(tài)字段的出現(xiàn),靜態(tài)塊也來了。 只在類創(chuàng)建時(shí)執(zhí)行一次代碼 — 就像C#和Java等OOP語(yǔ)言中的靜態(tài)構(gòu)造函數(shù)。 所以你可以在類中創(chuàng)建任意多個(gè)靜態(tài)塊 — 所有代碼都會(huì)按你定義的順序運(yùn)行:
class Vehicle {
static defaultColor = 'blue';
}
class Car extends Vehicle {
static colors = [];
// ?? pushes red before green
// ?? 先添加 red,然后添加 green
static {
this.colors.push(super.defaultColor, 'red');
}
static {
this.colors.push('green');
}
}
console.log(Car.colors); // ['blue', 'red', 'green']
5. 錯(cuò)誤報(bào)告升級(jí)
有時(shí)我們捕獲調(diào)用棧下方方法的錯(cuò)誤,只是為了將其重新拋出回調(diào)用棧上方。 但當(dāng)我們這樣做時(shí),我們會(huì)失去原始錯(cuò)誤中的關(guān)鍵信息:
try {
userAction();
} catch (err) {
// ? doesn't know fundamental cause of error
// ? 不知道錯(cuò)誤的根本原因
console.log(err);
}
function userAction() {
try {
apiCallThatCanThrow();
} catch (err) {
// ?? rethrow
// ?? 重新拋出錯(cuò)誤
throw new Error('New error message');
}
}
function apiCallThatCanThrow() {
console.log('fetching from codingbeautydev.com...');
throw new Error('throwing for no reason');
}
這就是為什么ES13引入了一個(gè)新的cause屬性來保留這個(gè)重要信息并使調(diào)試更容易:
try {
userAction();
} catch (err) {
// ? now knows what caused the error
// ? 現(xiàn)在知道了錯(cuò)誤的原因
console.log(err);
console.log(`Caused by: ${err.cause}`);
}
function userAction() {
try {
apiCallThatCanThrow();
} catch (err) {
// ? error cause
// ? 錯(cuò)誤原因
throw new Error('New error message', { cause: err });
}
}
function apiCallThatCanThrow() {
console.log('fetching from codingbeautydev.com...');
throw new Error('throwing for no reason');
}
最后的思考
總的來說,ES13對(duì)JavaScript來說是一個(gè)重大飛躍,它帶來了幾個(gè)已成為現(xiàn)代開發(fā)必不可少的特性。 使你能夠編寫更清晰、更簡(jiǎn)潔、更具表現(xiàn)力的代碼。