新的 ES2022 規(guī)范終于發(fā)布了,我總結(jié)了8個(gè)實(shí)用的新功能

英文 | https://betterprogramming.pub/es2022-features-javascript-a9f8f5dcba5a

新的 ES13 規(guī)范終于發(fā)布了。
JavaScript 不是一種開(kāi)源語(yǔ)言,它是一種需要遵循 ECMAScript 標(biāo)準(zhǔn)規(guī)范編寫(xiě)的語(yǔ)言,TC39 委員會(huì)負(fù)責(zé)討論和批準(zhǔn)新功能的發(fā)布, 那TC39他們是誰(shuí)?
“ECMA International 的 TC39 是一群 JavaScript 開(kāi)發(fā)人員、實(shí)施者、學(xué)者等,他們與社區(qū)合作維護(hù)和發(fā)展 JavaScript 的定義。” — TC39.es
他們的發(fā)布過(guò)程由五個(gè)階段組成,自 2015 年以來(lái),他們一直在進(jìn)行年度發(fā)布,它們通常發(fā)生在春天舉行發(fā)布。
有兩種方法可以引用任何 ECMAScript 版本:
按年份:這個(gè)新版本將是 ES2022。
按其迭代次數(shù):這個(gè)新版本將是第 13 次迭代,所以它可以被稱(chēng)為 ES13。
那么這次這個(gè)版本有什么新東西呢?我們可以對(duì)哪些功能感到興奮?
01、正則表達(dá)式匹配索引
目前,在 JavaScript 中使用 JavaScript Regex API 時(shí),僅返回匹配的開(kāi)始索引。但是,對(duì)于一些特殊的高級(jí)場(chǎng)景,這還不夠。
作為這些規(guī)范的一部分,添加了一個(gè)特殊的標(biāo)志 d。通過(guò)使用它,正則表達(dá)式 API 將返回一個(gè)二維數(shù)組作為名索引的鍵。它包含每個(gè)匹配項(xiàng)的開(kāi)始和結(jié)束索引。如果在正則表達(dá)式中捕獲了任何命名組,它將在 indices.groups 對(duì)象中返回它們的開(kāi)始/結(jié)束索引, 命名的組名將是它的鍵。

// ? a regex with a 'B' named group capture
const expr = /a+(?<B>b+)+c/d;

const result = expr.exec("aaabbbc")

// ? shows start-end matches + named group match
console.log(result.indices);
// prints [Array(2), Array(2), groups: {…}]

// ? showing the named 'B' group match
console.log(result.indices.groups['B'])
// prints [3, 6]
查看原始提案,https://github.com/tc39/proposal-regexp-match-indices

02、Top-level await

在此提案之前,不接受Top-level await,但有一些變通方法可以模擬這種行為,但其有缺點(diǎn)。

Top-level await 特性讓我們依靠模塊來(lái)處理這些 Promise。這是一個(gè)直觀的功能。

但是請(qǐng)注意,它可能會(huì)改變模塊的執(zhí)行順序, 如果一個(gè)模塊依賴(lài)于另一個(gè)具有Top-level await 調(diào)用的模塊,則該模塊的執(zhí)行將暫停,直到 promise 完成。

讓我們看一個(gè)例子:

// users.js
export const users = await fetch('/users/lists');

// usage.js
import { users } from "./users.js";
// ? the module will wait for users to be fullfilled prior to executing any code
console.log(users);
在上面的示例中,引擎將等待用戶(hù)完成操作,然后,再執(zhí)行 usage.js 模塊上的代碼。

總之,這是一個(gè)很好且直觀的功能,需要小心使用,我們不要濫用它。

在此處查看原始提案。https://github.com/tc39/proposal-top-level-await

03、.at( )

長(zhǎng)期以來(lái),一直有人要求 JavaScript 提供類(lèi)似 Python 的數(shù)組負(fù)索引訪(fǎng)問(wèn)器。而不是做 array[array.length-1] 來(lái)做簡(jiǎn)單的 array[-1]。這是不可能的,因?yàn)?[] 符號(hào)也用于 JavaScript 中的對(duì)象。

被接受的提案采取了更實(shí)際的方法。Array 對(duì)象現(xiàn)在將有一個(gè)方法來(lái)模擬上述行為。

const array = [1,2,3,4,5,6]

// ? When used with positive index it is equal to [index]
array.at(0) // 1
array[0] // 1

// ? When used with negative index it mimicks the Python behaviour
array.at(-1) // 6
array.at(-2) // 5
array.at(-4) // 3
查看原始提案,https://github.com/tc39/proposal-relative-indexing-method

順便說(shuō)一句,既然我們?cè)谡務(wù)摂?shù)組,你知道你可以解構(gòu)數(shù)組位置嗎?

const array = [1,2,3,4,5,6];

// ? Different ways of accessing the third position
const {3: third} = array; // third = 4
array.at(3) // 4
array[3] // 4
04、可訪(fǎng)問(wèn)的 Object.prototype.hasOwnProperty

以下只是一個(gè)很好的簡(jiǎn)化, 已經(jīng)有了 hasOwnProperty。但是,它需要在我們想要執(zhí)行的查找實(shí)例中調(diào)用。因此,許多開(kāi)發(fā)人員最終會(huì)這樣做是很常見(jiàn)的:

const x = { foo: "bar" };

// ? grabbing the hasOwnProperty function from prototype
const hasOwnProperty = Object.prototype.hasOwnProperty

// ? executing it with the x context
if (hasOwnProperty.call(x, "foo")) {
  ...
}





通過(guò)這些新規(guī)范,一個(gè) hasOwn 方法被添加到 Object 原型中,現(xiàn)在,我們可以簡(jiǎn)單地做:

const x = { foo: "bar" };

// ? using the new Object method
if (Object.hasOwn(x, "foo")) {
  ...
}
查看原始提案,https://github.com/tc39/proposal-accessible-object-hasownproperty

05、Error Cause

錯(cuò)誤幫助我們識(shí)別應(yīng)用程序的意外行為并做出反應(yīng),然而,理解深層嵌套錯(cuò)誤的根本原因,正確處理它們可能會(huì)變得具有挑戰(zhàn)性,在捕獲和重新拋出它們時(shí),我們會(huì)丟失堆棧跟蹤信息。

沒(méi)有關(guān)于如何處理的明確協(xié)議,考慮到任何錯(cuò)誤處理,我們至少有 3 個(gè)選擇:

async function fetchUserPreferences() {
  try {
    const users = await fetch('//user/preferences')
      .catch(err => {
        // What is the best way to wrap the error?
        // 1. throw new Error('Failed to fetch preferences ' + err.message);
        // 2. const wrapErr = new Error('Failed to fetch preferences');
        //    wrapErr.cause = err;
        //    throw wrapErr;
        // 3. class CustomError extends Error {
        //      constructor(msg, cause) {
        //        super(msg);
        //        this.cause = cause;
        //      }
        //    }
        //    throw new CustomError('Failed to fetch preferences', err);
      })
    }
}

fetchUserPreferences();
作為這些新規(guī)范的一部分,我們可以構(gòu)造一個(gè)新錯(cuò)誤并保留獲取的錯(cuò)誤的引用。 我們只需將對(duì)象 {cause: err} 傳遞給 Errorconstructor。

這一切都變得更簡(jiǎn)單、標(biāo)準(zhǔn)且易于理解深度嵌套的錯(cuò)誤, 讓我們看一個(gè)例子:

async function fetcUserPreferences() {
  try {
    const users = await fetch('//user/preferences')
      .catch(err => {
        throw new Error('Failed to fetch user preferences, {cause: err});
      })
    }
}

fetcUserPreferences();
了解有關(guān)該提案的更多信息,https://github.com/tc39/proposal-error-cause

06、Class Fields

在此版本之前,沒(méi)有適當(dāng)?shù)姆椒▉?lái)創(chuàng)建私有字段, 通過(guò)使用提升有一些方法可以解決它,但它不是一個(gè)適當(dāng)?shù)乃接凶侄巍?但現(xiàn)在很簡(jiǎn)單, 我們只需要將 # 字符添加到我們的變量聲明中。

class Foo {
  #iteration = 0;

  increment() {
    this.#iteration++;
  }

  logIteration() {
    console.log(this.#iteration);
  }
}

const x = new Foo();

// ? Uncaught SyntaxError: Private field '#iteration' must be declared in an enclosing class
x.#iteration

// ? works
x.increment();

// ? works
x.logIteration();
擁有私有字段意味著我們擁有強(qiáng)大的封裝邊界, 無(wú)法從外部訪(fǎng)問(wèn)類(lèi)變量,這表明 class 關(guān)鍵字不再只是糖語(yǔ)法。

我們還可以創(chuàng)建私有方法:

class Foo {
  #iteration = 0;

  #auditIncrement() {
    console.log('auditing');
  }

  increment() {
    this.#iteration++;
    this.#auditIncrement();
  }
}

const x = new Foo();

// ? Uncaught SyntaxError: Private field '#auditIncrement' must be declared in an enclosing class
x.#auditIncrement

// ? works
x.increment();





該功能與私有類(lèi)的類(lèi)靜態(tài)塊和人體工程學(xué)檢查有關(guān),我們將在接下來(lái)的內(nèi)容中看到。

了解有關(guān)該提案的更多信息,https://github.com/tc39/proposal-class-fields

07、Class Static Block

作為新規(guī)范的一部分,我們現(xiàn)在可以在任何類(lèi)中包含靜態(tài)塊,它們將只運(yùn)行一次,并且是裝飾或執(zhí)行類(lèi)靜態(tài)端的某些字段初始化的好方法。

我們不限于使用一個(gè)塊,我們可以擁有盡可能多的塊。

// ? will output 'one two three'
class A {
  static {
      console.log('one');
  }
  static {
      console.log('two');
  }
  static {
      console.log('three');
  }
}
他們有一個(gè)不錯(cuò)的獎(jiǎng)金,他們獲得對(duì)私有字段的特權(quán)訪(fǎng)問(wèn), 你可以用它們來(lái)做一些有趣的模式。

let getPrivateField;

class A {
  #privateField;
  constructor(x) {
    this.#privateField = x;
  }
  static {
    // ? it can access any private field
    getPrivateField = (a) => a.#privateField;
  }
}

const a = new A('foo');
// ? Works, foo is printed
console.log(getPrivateField(a));
如果我們嘗試從實(shí)例對(duì)象的外部范圍訪(fǎng)問(wèn)該私有變量,我們將得到無(wú)法從類(lèi)未聲明它的對(duì)象中讀取私有成員#privateField。

了解有關(guān)該提案的更多信息,https://github.com/tc39/proposal-class-static-block

08、Private Fields

新的私有字段是一個(gè)很棒的功能,但是,在某些靜態(tài)方法中檢查字段是否為私有可能會(huì)變得很方便。

嘗試在類(lèi)范圍之外調(diào)用它會(huì)導(dǎo)致我們之前看到的相同錯(cuò)誤。

class Foo {
  #brand;

  static isFoo(obj) {
    return #brand in obj;
  }
}

const x = new Foo();

// ? works, it returns true
Foo.isFoo(x);

// ? works, it returns false
Foo.isFoo({})

// ? Uncaught SyntaxError: Private field '#brand' must be declared in an enclosing class
#brand in x
了解有關(guān)該提案的更多信息。https://github.com/tc39/proposal-private-fields-in-in

最后的想法

這是一個(gè)有趣的版本,它提供了許多小而有用的功能,例如 at、private fields和error cause。當(dāng)然,error cause會(huì)給我們的日常錯(cuò)誤跟蹤任務(wù)帶來(lái)很多清晰度。

一些高級(jí)功能,如top-level await,在使用它們之前需要很好地理解。它們可能在你的代碼執(zhí)行中產(chǎn)生不必要的副作用。

我希望這篇文章能讓你和我一樣對(duì)新的 ES2022 規(guī)范感到興奮,請(qǐng)記得點(diǎn)贊我,關(guān)注我。

最后,感謝你的閱讀。

作者:前端Q


歡迎關(guān)注微信公眾號(hào) :前端Q