是時候對JavaScipt進行更新。本文我們一起回顧來自ES2020的最新的和最偉大的功能。
安裝
因為很多人不以為更新瀏覽器可以減輕開發者的工作, 我們需要借助babel來使得用戶可以使用不發使用的功能。為了這個簡單的目標,我們使用Parcel bundler讓一切盡可能快的運行起來。
$ yarn add parcel-bundler
package.json
"script": {
"start": "parcel index.html"
}
可惜的是, 因為此時我們寫的東西超前所以沒有關於ES2020的預解析。如果你把以下內容保存到.babelrc文件, Parcel會幫你進行相關安裝。
.babelrc
{
"plugins": [
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-private-methods",
"@babel/plugin-syntax-bigint"
]
}
class的私有變量
class主要目的之一是將代碼包含到更多可重復使用的模塊中去。我們創建一個class使用在很多不同的地方, 但是你可能並不希望他全部的內部東西全局可用。
現在, 通過在變量和函數前添加一個簡單的hash標志(#), 這個標志可以全部保留到class內部使用。
class Message {
#message = "Howdy"
greet() { console.log(this.#message) }
}
const greeting = new Message()
greeting.greet() // Howdy
console.log(greeting.#message) // Private name #message is not defined
Promise.allSettled
當和多個promise同時工作的時候, 尤其他們相互依賴時, 記錄調試錯誤發生了什么是很有用的。借助Promise.allSettled
我們可以創建一個當所有promise都完成時才返回的promise。我們可以訪問包含每個promise數據的數組。
const p1 = new Promise((res, rej) => setTimeout(res, 1000));
const p2 = new Promise((res, rej) => setTimeout(rej, 1000));
Promise.allSettled([p1, p2]).then(data => console.log(data));
// [
// Object { status: "fulfilled", value: undefined},
// Object { status: "rejected", reason: undefined}
// ]
Nullish Coalescing Operator(空合並運算符)
因為JavaScript是動態類型, 在分配變量時, 我們需要記住JavaScript對真/假值的處理。假如我們有一個具有多個變量的對象, 有時我們允許想空對象或者數組0這樣的假值。設置默認值很快會變得很煩人, 因為他會覆蓋應該是有效的值。
let person = {
profile: {
name: "",
age: 0
}
};
console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18
我們使用兩個問號(空合並運算符)替代邏輯與運算符使類型更加嚴格, 這樣做僅允許null或者undefined設置默認值。
console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0
Optional Chaining Operator
與前一個運算相似, JavaScript在假值處理時, 可能不會按照我們的預期進行操作。如果是undefined則返回一個值, 但是如果得到這個值之前出現undefined怎么辦?
我們在.
之前加問號可以使路徑的任何部分變為可選, 以至於可以進行交互。
let person = {};
console.log(person.profile.name ?? "Anonymous"); // person.profile is undefined
console.log(person?.profile?.name ?? "Anonymous");
console.log(person?.profile?.age ?? 18);
BigInt
我們不想探究JavaScript如何操作數字的技術細節, 但是當數字足夠大時變得不穩定。JavaScript中可操作的最大值是2^53, 即MAX_SAFE_INTEGER。
const max = Number.MAX_SAFE_INTEGER;
console.log(max); // 9007199254740991
上邊的事情開始變得有點不可思議...
console.log(max + 1); // 9007199254740992
console.log(max + 2); // 9007199254740992
console.log(max + 3); // 9007199254740994
console.log(Math.pow(2, 53) == Math.pow(2, 53) + 1); // true
我們用一個新的new BigInt來回避這個問題。通過在尾部加n
對超級大的數字進行操作。我們無法把標准數字和BIgInt進行混合, 因此需要運算的需要都是BigInt型。
const bigNum = 100000000000000000000000000000n;
console.log(bigNum * 2n); // 200000000000000000000000000000n
Dynamic Import
假如你有一個全部是工具函數的文件, 文件中的大部分很少使用且全部導入他們的依賴浪費資源。現在我們使用async/await
在需要的地方動態導入我們的依賴。
const add = (num1, num2) => num1 + num2;
export { add };
const doMath = async (num1, num2) => {
if (num1 && num2) {
const math = await import('./math.js');
console.log(math.add(5, 10));
};
};
doMath(4, 2);