類的主要目的之一是把咱們的代碼複用到更多模塊中去,可是咱們又不但願把全部的屬性和方法都暴露出來,如今,有了這個新特性,咱們就能夠很輕易的實現這個想法了,只須要在咱們的私有屬性或者方法前面加一個 # 號便可:node
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,尤爲是這些 promise 有依賴關係時,打印每一個 promise 的日誌顯得尤其重要,這能夠幫助咱們調試錯誤。有了 Promise.allSelected,咱們能夠建立一個新的 promise,這個 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} // ]
因爲 JavaScript 的類型時動態的,在分配變量時,咱們不得不去記住哪些值會被判斷爲真,哪些會被判斷爲假。當咱們在建立一個對象時,一般會初始化屬性爲假的值,好比一個空字符串 或者是 0。設置默認值就會變得很煩人,由於它會覆蓋有效值,看下以下 demo,你就會發現這麼處理真的很煩人:promise
let person = { profile: { name: "", age: 0 } }; console.log(person.profile.name || "Anonymous"); // Anonymous console.log(person.profile.age || 18); // 18
上述例子中,可能結果並非咱們想要的,咱們想名字爲空或者 0 歲也是合理的,應該不被代替,咱們能夠用 ?? 運算符替換掉 || 運算符,由於 ?? 運算符的類型檢測會更嚴格一點,它只會把 null 和 undefined 判斷爲 false。async
console.log(person.profile.name ?? "Anonymous"); // "" console.log(person.profile.age ?? 18); // 0
與空值合併運算符相似,JavaScript 在處理虛假值時,可能沒法按照咱們的意願進行操做。當屬性值未定義時,咱們能夠返回一個默認值,可是若是屬性的路徑未被定義呢?函數
答案是,能夠經過在點符號前添加問號,咱們能夠將屬性路徑的任何部分設置爲可選,以便操做。網站
let person = {}; console.log(person.profile.name ?? "Anonymous"); // person.profile is undefined console.log(person?.profile?.name ?? "Anonymous"); // Anonymous console.log(person?.profile?.age ?? 18); // 18
一般,咱們不會深刻技術細節,可是因爲 JavaScript 處理數字的方式,當你把研究的更加深刻時,事情就會變得有點不靠譜。 Javascript 能夠處理的最大數字是2 ^ 53,咱們能夠用 MAX safe integer 看到。this
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
咱們可使用新的數據類型 BigInt 來處理上述問題。只需在數字後面加個符號 n,咱們就能夠瘋狂的使用大的數值了。咱們不能用 BigInt 數字混淆標準數字,因此通常在數學計算時使用 BigInt 類型。調試
const bigNum = 100000000000000000000000000000n; console.log(bigNum * 2n); // 200000000000000000000000000000n
若是咱們有不少的功能函數,有些是不多用的,那麼一塊兒導入會使資源浪費,如今咱們可使用 async/await 來動態導入這些依賴了,可是這個方法僅適用於 node.js 環境。日誌
// math.js 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);
翻譯自:https://alligator.io/js/es2020/
原創文章,首發於我的網站,轉載請註明出處