Promise[Symbol.species]

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

Promise[Symbol.species] 靜態訪問器屬性返回用於從 Promise 方法構建返回值(return value)的建構函式。

警告: [Symbol.species] 的存在允許執行任意程式碼,並可能產生安全漏洞。它還會使某些最佳化變得更加困難。引擎實現者正在 調查是否要移除此功能。如果可能,請避免依賴它。

語法

js
Promise[Symbol.species]

返回值

呼叫 get [Symbol.species] 時,建構函式 (this) 的值。返回值用於從構建新 Promise 的 Promise 鏈式方法(promise chaining methods)構建返回值。

描述

[Symbol.species] 訪問器屬性返回 Promise 物件的預設建構函式。子類建構函式可以重寫它以更改建構函式分配。預設實現基本上是

js
// Hypothetical underlying implementation for illustration
class Promise {
  static get [Symbol.species]() {
    return this;
  }
}

由於這種多型實現,派生子類的 [Symbol.species] 預設情況下也將返回建構函式本身。

js
class SubPromise extends Promise {}
SubPromise[Symbol.species] === SubPromise; // true

Promise 鏈式方法 — then()catch()finally() — 會返回新的 Promise 物件。它們透過 this.constructor[Symbol.species] 獲取用於構造新 Promise 的建構函式。如果 this.constructorundefined,或者 this.constructor[Symbol.species]undefinednull,則使用預設的 Promise() 建構函式。否則,將使用 this.constructor[Symbol.species] 返回的建構函式來構造新的 Promise 物件。

示例

普通物件中的 species

Symbol.species 屬性返回預設建構函式,即 PromisePromise 建構函式。

js
Promise[Symbol.species]; // [Function: Promise]

派生物件中的 species

在自定義 Promise 子類的例項中,例如 MyPromiseMyPromise 的 species 是 MyPromise 建構函式。但是,您可能希望重寫它,以便在派生類的方法中返回父 Promise 物件。

js
class MyPromise extends Promise {
  // Override MyPromise species to the parent Promise constructor
  static get [Symbol.species]() {
    return Promise;
  }
}

預設情況下,Promise 方法將返回子類型別的 Promise。

js
class MyPromise extends Promise {
  someValue = 1;
}

console.log(MyPromise.resolve(1).then(() => {}).someValue); // 1

透過重寫 [Symbol.species],Promise 方法將返回基礎 Promise 型別。

js
class MyPromise extends Promise {
  someValue = 1;
  static get [Symbol.species]() {
    return Promise;
  }
}

console.log(MyPromise.resolve(1).then(() => {}).someValue); // undefined

規範

規範
ECMAScript® 2026 語言規範
# sec-get-promise-%symbol.species%

瀏覽器相容性

另見