天天看點

新的 ES2022 規範終于釋出了,我總結了8個實用的新功能

新的 ES2022 規範終于釋出了,我總結了8個實用的新功能

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

新的 ES13 規範終于釋出了。 

JavaScript 不是一種開源語言,它是一種需要遵循 ECMAScript 标準規範編寫的語言,TC39 委員會負責讨論和準許新功能的釋出, 那TC39他們是誰?

“ECMA International 的 TC39 是一群 JavaScript 開發人員、實施者、學者等,他們與社群合作維護和發展 JavaScript 的定義。” — TC39.es

他們的釋出過程由五個階段組成,自 2015 年以來,他們一直在進行年度釋出,它們通常發生在春天舉行釋出。

有兩種方法可以引用任何 ECMAScript 版本:

  • 按年份:這個新版本将是 ES2022。
  • 按其疊代次數:這個新版本将是第 13 次疊代,是以它可以被稱為 ES13。

那麼這次這個版本有什麼新東西呢?我們可以對哪些功能感到興奮?

01、正規表達式比對索引

目前,在 JavaScript 中使用 JavaScript Regex API 時,僅傳回比對的開始索引。但是,對于一些特殊的進階場景,這還不夠。

作為這些規範的一部分,添加了一個特殊的标志 d。通過使用它,正規表達式 API 将傳回一個二維數組作為名索引的鍵。它包含每個比對項的開始和結束索引。如果在正規表達式中捕獲了任何命名組,它将在 indices.groups 對象中傳回它們的開始/結束索引, 命名的組名将是它的鍵。

// ✅ 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,但有一些變通方法可以模拟這種行為,但其有缺點。

Top-level await 特性讓我們依靠子產品來處理這些 Promise。這是一個直覺的功能。 

但是請注意,它可能會改變子產品的執行順序, 如果一個子產品依賴于另一個具有Top-level await 調用的子產品,則該子產品的執行将暫停,直到 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);      

在上面的示例中,引擎将等待使用者完成操作,然後,再執行 usage.js 子產品上的代碼。

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

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

03、.at( )

長期以來,一直有人要求 JavaScript 提供類似 Python 的數組負索引通路器。而不是做 array[array.length-1] 來做簡單的 array[-1]。這是不可能的,因為 [] 符号也用于 JavaScript 中的對象。

被接受的提案采取了更實際的方法。Array 對象現在将有一個方法來模拟上述行為。

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

順便說一句,既然我們在談論數組,你知道你可以解構數組位置嗎? 

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

以下隻是一個很好的簡化, 已經有了 hasOwnProperty。但是,它需要在我們想要執行的查找執行個體中調用。是以,許多開發人員最終會這樣做是很常見的:

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")) {
  ...
}      

通過這些新規範,一個 hasOwn 方法被添加到 Object 原型中,現在,我們可以簡單地做:

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

錯誤幫助我們識别應用程式的意外行為并做出反應,然而,了解深層嵌套錯誤的根本原因,正确處理它們可能會變得具有挑戰性,在捕獲和重新抛出它們時,我們會丢失堆棧跟蹤資訊。

沒有關于如何處理的明确協定,考慮到任何錯誤處理,我們至少有 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();      

作為這些新規範的一部分,我們可以構造一個新錯誤并保留擷取的錯誤的引用。 我們隻需将對象 {cause: err} 傳遞給 Errorconstructor。

這一切都變得更簡單、标準且易于了解深度嵌套的錯誤, 讓我們看一個例子:

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


fetcUserPreferences();      

了解有關該提案的更多資訊,https://github.com/tc39/proposal-error-cause

06、Class Fields

在此版本之前,沒有适當的方法來建立私有字段, 通過使用提升有一些方法可以解決它,但它不是一個适當的私有字段。 但現在很簡單, 我們隻需要将 # 字元添加到我們的變量聲明中。

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();      

擁有私有字段意味着我們擁有強大的封裝邊界, 無法從外部通路類變量,這表明 class 關鍵字不再隻是糖文法。

我們還可以建立私有方法:

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();      

該功能與私有類的類靜态塊和人體工程學檢查有關,我們将在接下來的内容中看到。

了解有關該提案的更多資訊,https://github.com/tc39/proposal-class-fields

07、Class Static Block

作為新規範的一部分,我們現在可以在任何類中包含靜态塊,它們将隻運作一次,并且是裝飾或執行類靜态端的某些字段初始化的好方法。

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

// ✅ will output 'one two three'
class A {
  static {
      console.log('one');
  }
  static {
      console.log('two');
  }
  static {
      console.log('three');
  }
}      

他們有一個不錯的獎金,他們獲得對私有字段的特權通路, 你可以用它們來做一些有趣的模式。

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));      

如果我們嘗試從執行個體對象的外部範圍通路該私有變量,我們将得到無法從類未聲明它的對象中讀取私有成員#privateField。

了解有關該提案的更多資訊,https://github.com/tc39/proposal-class-static-block

08、Private Fields

新的私有字段是一個很棒的功能,但是,在某些靜态方法中檢查字段是否為私有可能會變得很友善。

嘗試在類範圍之外調用它會導緻我們之前看到的相同錯誤。

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      

了解有關該提案的更多資訊。https://github.com/tc39/proposal-private-fields-in-in

最後的想法

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

一些進階功能,如top-level await,在使用它們之前需要很好地了解。它們可能在你的代碼執行中産生不必要的副作用。

我希望這篇文章能讓你和我一樣對新的 ES2022 規範感到興奮,請記得點贊我,關注我。

繼續閱讀