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

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

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

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

讓我們看一個例子:

// 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);
在上面的示例中,引擎將等待用戶完成操作,然后,再執(zhí)行 usage.js 模塊上的代碼。

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

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

03、.at( )

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

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

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

順便說一句,既然我們在談?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、可訪問的 Object.prototype.hasOwnProperty

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

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ī)范,一個 hasOwn 方法被添加到 Object 原型中,現(xià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

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

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

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)造一個新錯誤并保留獲取的錯誤的引用。 我們只需將對象 {cause: err} 傳遞給 Errorconstructor。

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

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

在此版本之前,沒有適當(dāng)?shù)姆椒▉韯?chuàng)建私有字段, 通過使用提升有一些方法可以解決它,但它不是一個適當(dāng)?shù)乃接凶侄巍?但現(xià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)大的封裝邊界, 無法從外部訪問類變量,這表明 class 關(guān)鍵字不再只是糖語法。

我們還可以創(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();





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

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

07、Class Static Block

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

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

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

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í)例對象的外部范圍訪問該私有變量,我們將得到無法從類未聲明它的對象中讀取私有成員#privateField。

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

08、Private Fields

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

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

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

最后的想法

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

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

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

最后,感謝你的閱讀。

作者:前端Q


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