javascript 是最流行的編程語(yǔ)言之一,每年都會(huì)添加新的特性。本文介紹了添加在 ecmascript 2020(又稱es11)中的新特性。
在引入 ECMAScript 2015(又稱 ES6)之前,JavaScript 發(fā)展的非常緩慢。但自 2015 年起,每年都有新特性添加進(jìn)來(lái)。需要注意的是,不是所有特性都被現(xiàn)代瀏覽器支持,但是由于 JavaScript 編譯器 Babel 的存在,我們已經(jīng)可以使用新特性了。本文將介紹 ECMAScript 2020(ES11)的一些最新特性。
Optional Chaining 可選鏈?zhǔn)秸{(diào)用
大部分開(kāi)發(fā)者都遇到過(guò)這個(gè)問(wèn)題:
TypeError: Cannot read property ‘x’ of undefined
這個(gè)錯(cuò)誤表示我們正在訪問(wèn)一個(gè)不屬于對(duì)象的屬性。
訪問(wèn)對(duì)象的屬性
const flower = { colors: { red: true } } console.log(flower.colors.red) // 正常運(yùn)行 console.log(flower.species.lily) // 拋出錯(cuò)誤:TypeError: Cannot read property 'lily' of undefined
在這種情況下,JavaScript 引擎會(huì)像這樣拋出錯(cuò)誤。但是某些情況下值是否存在并不重要,因?yàn)槲覀冎浪鼤?huì)存在。于是,可選鏈?zhǔn)秸{(diào)用就派上用場(chǎng)了!
我們可以使用由一個(gè)問(wèn)號(hào)和一個(gè)點(diǎn)組成的可選鏈?zhǔn)讲僮鞣?,去表示不?yīng)該引發(fā)錯(cuò)誤。如果沒(méi)有值,應(yīng)該返回 undefined。
console.log(flower.species?.lily) // 輸出 undefined
當(dāng)訪問(wèn)數(shù)組或調(diào)用函數(shù)時(shí),也可以使用可選鏈?zhǔn)秸{(diào)用。
訪問(wèn)數(shù)組
let flowers = ['lily', 'daisy', 'rose'] console.log(flowers[1]) // 輸出:daisy flowers = null console.log(flowers[1]) // 拋出錯(cuò)誤:TypeError: Cannot read property '1' of null console.log(flowers?.[1]) // 輸出:undefined
調(diào)用函數(shù)
let plantFlowers = () => { return 'orchids' } console.log(plantFlowers()) // 輸出:orchids plantFlowers = null console.log(plantFlowers()) // 拋出錯(cuò)誤:TypeError: plantFlowers is not a function console.log(plantFlowers?.()) // 輸出:undefined
Nullish Coalescing 空值合并
目前,要為變量提供回退值,邏輯操作符 || 還是必須的。它適用于很多情況,但不能應(yīng)用在一些特殊的場(chǎng)景。例如,初始值是布爾值或數(shù)字的情況。舉例說(shuō)明,我們要把數(shù)字賦值給一個(gè)變量,當(dāng)變量的初始值不是數(shù)字時(shí),就默認(rèn)其為 7 :
let number = 1 let myNumber = number || 7
變量 myNumber 等于 1,因?yàn)樽筮叺模╪umber)是一個(gè) 真 值 1。但是,當(dāng)變量 number 不是 1 而是 0 呢?
let number = 0 let myNumber = number || 7
0 是?假?值,所以即使 0 是數(shù)字。變量?myNumber?將會(huì)被賦值為右邊的 7。但結(jié)果并不是我們想要的。幸好,由兩個(gè)問(wèn)號(hào)組成:???的合并操作符就可以檢查變量?number?是否是一個(gè)數(shù)字,而不用寫(xiě)額外的代碼了。
let number = 0 let myNumber = number ?? 7
操作符右邊的值僅在左邊的值等于 null 或 undefined 時(shí)有效,因此,例子中的變量 myNumber 現(xiàn)在的值等于 0 了。
Private Fields 私有字段
許多具有 classes 的編程語(yǔ)言允許定義類作為公共的,受保護(hù)的或私有的屬性。Public 屬性可以從類的外部或者子類訪問(wèn),protected 屬性只能被子類訪問(wèn),private 屬性只能被類內(nèi)部訪問(wèn)。JavaScript 從 ES6 開(kāi)始支持類語(yǔ)法,但直到現(xiàn)在才引入了私有字段。要定義私有屬性,必須在其前面加上散列符號(hào):#。
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) // 報(bào)錯(cuò):SyntaxError: Private field '#leaf_color' must be declared in an enclosing class
如果我們從外部訪問(wèn)類的私有屬性,勢(shì)必會(huì)報(bào)錯(cuò)。
Static Fields 靜態(tài)字段
如果想使用類的方法,首先必須實(shí)例化一個(gè)類,如下所示:
class Flower { add_leaves() { console.log("Adding leaves"); } } const rose = new Flower(); rose.add_leaves(); Flower.add_leaves() // 拋出錯(cuò)誤:TypeError: Flower.add_leaves is not a function
試圖去訪問(wèn)沒(méi)有實(shí)例化的?Flower?類的方法將會(huì)拋出一個(gè)錯(cuò)誤。但由于?static?字段,類方法可以被?static?關(guān)鍵詞聲明然后從外部調(diào)用。
class Flower { constructor(type) { this.type = type; } static create_flower(type) { return new Flower(type); } } const rose = Flower.create_flower("rose"); // 正常運(yùn)行
Top Level Await 頂級(jí) Await
目前,如果用?await?獲取 promise 函數(shù)的結(jié)果,那使用?await?的函數(shù)必須用?async?關(guān)鍵字定義。
const func = async () => { const response = await fetch(url) }
頭疼的是,在全局作用域中去等待某些結(jié)果基本上是不可能的。除非使用?立即調(diào)用的函數(shù)表達(dá)式(IIFE)。
(async () => { const response = await fetch(url) })()
但引入了?頂級(jí) Await?后,不需要再把代碼包裹在一個(gè) async 函數(shù)中了,如下即可:
const response = await fetch(url)
這個(gè)特性對(duì)于解決模塊依賴或當(dāng)初始源無(wú)法使用而需要備用源的時(shí)候是非常有用的。
let Vue try { Vue = await import('url_1_to_vue') } catch { Vue = await import('url_2_to_vue) }
Promise.allSettled 方法
等待多個(gè) promise 返回結(jié)果時(shí),我們可以用 Promise.all([promise_1, promise_2])。但問(wèn)題是,如果其中一個(gè)請(qǐng)求失敗了,就會(huì)拋出錯(cuò)誤。然而,有時(shí)候我們希望某個(gè)請(qǐng)求失敗后,其他請(qǐng)求的結(jié)果能夠正常返回。針對(duì)這種情況 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 將返回一個(gè)包含 status 和 value 的對(duì)象,失敗的 promise 將返回一個(gè)包含 status 和 reason 的對(duì)象。
Dynamic Import 動(dòng)態(tài)引入
你也許在 webpack 的模塊綁定中已經(jīng)使用過(guò)動(dòng)態(tài)引入。但對(duì)于該特性的原生支持已經(jīng)到來(lái):
// Alert.js export default { show() { // 代碼 } } // 使用 Alert.js 的文件 import('/components/Alert.js') .then(Alert => { Alert.show() })
考慮到許多應(yīng)用程序使用諸如 webpack 之類的模塊打包器來(lái)進(jìn)行代碼的轉(zhuǎn)譯和優(yōu)化,這個(gè)特性現(xiàn)在還沒(méi)什么大作用。
MatchAll 匹配所有項(xiàng)
如果你想要查找字符串中所有正則表達(dá)式的匹配項(xiàng)和它們的位置,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?返回更多的信息,包括找到匹配項(xiàng)的索引。
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 // ]
globalThis 全局對(duì)象
JavaScript 可以在不同環(huán)境中運(yùn)行,比如瀏覽器或者 Node.js。瀏覽器中可用的全局對(duì)象是變量 window,但在 Node.js 中是一個(gè)叫做 global 的對(duì)象。為了在不同環(huán)境中都使用統(tǒng)一的全局對(duì)象,引入了 globalThis 。
// 瀏覽器 window == globalThis // true // node.js global == globalThis // true
BigInt
JavaScript 中能夠精確表達(dá)的最大數(shù)字是 2^53 - 1。而 BigInt 可以用來(lái)創(chuàng)建更大的數(shù)字
const theBiggerNumber = 9007199254740991n const evenBiggerNumber = BigInt(9007199254740991)
結(jié)論
我希望這篇文章對(duì)您有用,并像我一樣期待 JavaScript 即將到來(lái)的新特性。如果想了解更多,可以看看 tc39 委員會(huì)的官方Github倉(cāng)庫(kù)。
推薦教程:《JS教程》
以上就是ECMAScript 2020 的新特性的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個(gè)人都需要一臺(tái)速度更快、更穩(wěn)定的 PC。隨著時(shí)間的推移,垃圾文件、舊注冊(cè)表數(shù)據(jù)和不必要的后臺(tái)進(jìn)程會(huì)占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)