- 原文地址:The Latest Features Added to JavaScript in ECMAScript 2020
- 原文做者:Thomas Findlay
- 譯文出自:掘金翻譯計劃
- 本文永久連接:github.com/xitu/gold-m…
- 譯者:Gesj-yean
- 校對者:Chorer,CoolRice
JavaScript 是最流行的編程語言之一,每一年都會添加新的特性。本文介紹了添加在 ECMAScript 2020(又稱ES11)中的新特性。javascript
在引入 ECMAScript 2015(又稱 ES6)以前,JavaScript 發展的很是緩慢。但自 2015 年起,每一年都有新特性添加進來。須要注意的是,不是全部特性都被現代瀏覽器支持,可是因爲 JavaScript 編譯器 Babel 的存在,咱們已經可使用新特性了。本文將介紹 ECMAScript 2020(ES11)的一些最新特性。前端
大部分開發者都遇到過這個問題:vue
TypeError: Cannot read property ‘x’ of undefined
java
這個錯誤表示咱們正在訪問一個不屬於對象的屬性。node
const flower = {
colors: {
red: true
}
}
console.log(flower.colors.red) // 正常運行
console.log(flower.species.lily) // 拋出錯誤:TypeError: Cannot read property 'lily' of undefined
複製代碼
在這種狀況下,JavaScript 引擎會像這樣拋出錯誤。可是某些狀況下值是否存在並不重要,由於咱們知道它會存在。因而,可選鏈式調用就派上用場了!android
咱們可使用由一個問號和一個點組成的可選鏈式操做符,去表示不該該引起錯誤。若是沒有值,應該返回 undefined。webpack
console.log(flower.species?.lily) // 輸出 undefined
複製代碼
當訪問數組或調用函數時,也可使用可選鏈式調用。ios
let flowers = ['lily', 'daisy', 'rose']
console.log(flowers[1]) // 輸出:daisy
flowers = null
console.log(flowers[1]) // 拋出錯誤:TypeError: Cannot read property '1' of null
console.log(flowers?.[1]) // 輸出:undefined
複製代碼
let plantFlowers = () => {
return 'orchids'
}
console.log(plantFlowers()) // 輸出:orchids
plantFlowers = null
console.log(plantFlowers()) // 拋出錯誤:TypeError: plantFlowers is not a function
console.log(plantFlowers?.()) // 輸出:undefined
複製代碼
目前,要爲變量提供回退值,邏輯操做符 ||
仍是必須的。它適用於不少狀況,但不能應用在一些特殊的場景。例如,初始值是布爾值或數字的狀況。舉例說明,咱們要把數字賦值給一個變量,當變量的初始值不是數字時,就默認其爲 7 :git
let number = 1
let myNumber = number || 7
複製代碼
變量 myNumber 等於 1,由於左邊的(number)是一個 真 值 1。可是,當變量 number 不是 1 而是 0 呢?github
let number = 0
let myNumber = number || 7
複製代碼
0 是 假 值,因此即便 0 是數字。變量 myNumber 將會被賦值爲右邊的 7。但結果並非咱們想要的。幸虧,由兩個問號組成:??
的合併操做符就能夠檢查變量 number 是不是一個數字,而不用寫額外的代碼了。
let number = 0
let myNumber = number ?? 7
複製代碼
操做符右邊的值僅在左邊的值等於 null 或 undefined 時有效,所以,例子中的變量 myNumber 如今的值等於 0 了。
許多具備 classes 的編程語言容許定義類做爲公共的,受保護的或私有的屬性。Public 屬性能夠從類的外部或者子類訪問,protected 屬性只能被子類訪問,private 屬性只能被類內部訪問。JavaScript 從 ES6 開始支持類語法,但直到如今才引入了私有字段。要定義私有屬性,必須在其前面加上散列符號:#
。
class Flower {
#leaf_color = "green";
constructor(name) {
this.name = name;
}
get_color() {
return this.#leaf_color;
}
}
const orchid = new Flower("orchid");
console.log(orchid.get_color()); // 輸出:green
console.log(orchid.#leaf_color) // 報錯:SyntaxError: Private field '#leaf_color' must be declared in an enclosing class
複製代碼
若是咱們從外部訪問類的私有屬性,勢必會報錯。
若是想使用類的方法,首先必須實例化一個類,以下所示:
class Flower {
add_leaves() {
console.log("Adding leaves");
}
}
const rose = new Flower();
rose.add_leaves();
Flower.add_leaves() // 拋出錯誤:TypeError: Flower.add_leaves is not a function
複製代碼
試圖去訪問沒有實例化的 Flower 類的方法將會拋出一個錯誤。但因爲 static 字段,類方法能夠被 static 關鍵詞聲明而後從外部調用。
class Flower {
constructor(type) {
this.type = type;
}
static create_flower(type) {
return new Flower(type);
}
}
const rose = Flower.create_flower("rose"); // 正常運行
複製代碼
目前,若是用 await 獲取 promise 函數的結果,那使用 await 的函數必須用 async 關鍵字定義。
const func = async () => {
const response = await fetch(url)
}
複製代碼
頭疼的是,在全局做用域中去等待某些結果基本上是不可能的。除非使用 當即調用的函數表達式(IIFE)。
(async () => {
const response = await fetch(url)
})()
複製代碼
但引入了 頂級 Await 後,不須要再把代碼包裹在一個 async 函數中了,以下便可:
const response = await fetch(url)
複製代碼
這個特性對於解決模塊依賴或當初始源沒法使用而須要備用源的時候是很是有用的。
let Vue
try {
Vue = await import('url_1_to_vue')
} catch {
Vue = await import('url_2_to_vue)
}
複製代碼
等待多個 promise 返回結果時,咱們能夠用 Promise.all([promise_1, promise_2])。但問題是,若是其中一個請求失敗了,就會拋出錯誤。然而,有時候咱們但願某個請求失敗後,其餘請求的結果可以正常返回。針對這種狀況 ES11 引入了 Promise.allSettled 。
promise_1 = Promise.resolve('hello')
promise_2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'problem'))
Promise.allSettled([promise_1, promise_2])
.then(([promise_1_result, promise_2_result]) => {
console.log(promise_1_result) // 輸出:{status: 'fulfilled', value: 'hello'}
console.log(promise_2_result) // 輸出:{status: 'rejected', reason: 'problem'}
})
複製代碼
成功的 promise 將返回一個包含 status 和 value 的對象,失敗的 promise 將返回一個包含 status 和 reason 的對象。
你也許在 webpack 的模塊綁定中已經使用過動態引入。但對於該特性的原生支持已經到來:
// Alert.js
export default {
show() {
// 代碼
}
}
// 使用 Alert.js 的文件
import('/components/Alert.js')
.then(Alert => {
Alert.show()
})
複製代碼
考慮到許多應用程序使用諸如 webpack 之類的模塊打包器來進行代碼的轉譯和優化,這個特性如今還沒什麼大做用。
若是你想要查找字符串中全部正則表達式的匹配項和它們的位置,MatchAll 很是有用。
const regex = /\b(apple)+\b/;
const fruits = "pear, apple, banana, apple, orange, apple";
for (const match of fruits.match(regex)) {
console.log(match);
}
// 輸出
//
// 'apple'
// 'apple'
複製代碼
相比之下,matchAll 返回更多的信息,包括找到匹配項的索引。
for (const match of fruits.matchAll(regex)) {
console.log(match);
}
// 輸出
//
// [
// 'apple',
// 'apple',
// index: 6,
// input: 'pear, apple, banana, apple, orange, apple',
// groups: undefined
// ],
// [
// 'apple',
// 'apple',
// index: 21,
// input: 'pear, apple, banana, apple, orange, apple',
// groups: undefined
// ],
// [
// 'apple',
// 'apple',
// index: 36,
// input: 'pear, apple, banana, apple, orange, apple',
// groups: undefined
// ]
複製代碼
JavaScript 能夠在不一樣環境中運行,好比瀏覽器或者 Node.js。瀏覽器中可用的全局對象是變量 window,但在 Node.js 中是一個叫作 global 的對象。爲了在不一樣環境中都使用統一的全局對象,引入了 globalThis 。
// 瀏覽器
window == globalThis // true
// node.js
global == globalThis // true
複製代碼
JavaScript 中可以精確表達的最大數字是 2^53 - 1。而 BigInt 能夠用來建立更大的數字。
const theBiggerNumber = 9007199254740991n
const evenBiggerNumber = BigInt(9007199254740991)
複製代碼
我但願這篇文章對您有用,並像我同樣期待 JavaScript 即將到來的新特性。若是想了解更多,能夠看看 tc39 委員會的官方Github倉庫。
若是發現譯文存在錯誤或其餘須要改進的地方,歡迎到 掘金翻譯計劃 對譯文進行修改並 PR,也可得到相應獎勵積分。文章開頭的 本文永久連接 即爲本文在 GitHub 上的 MarkDown 連接。
掘金翻譯計劃 是一個翻譯優質互聯網技術文章的社區,文章來源爲 掘金 上的英文分享文章。內容覆蓋 Android、iOS、前端、後端、區塊鏈、產品、設計、人工智能等領域,想要查看更多優質譯文請持續關注 掘金翻譯計劃、官方微博、知乎專欄。