Promise[Symbol.species]
Promise[Symbol.species] 靜態訪問器屬性返回用於從 Promise 方法構建返回值(return value)的建構函式。
警告: [Symbol.species] 的存在允許執行任意程式碼,並可能產生安全漏洞。它還會使某些最佳化變得更加困難。引擎實現者正在 調查是否要移除此功能。如果可能,請避免依賴它。
語法
Promise[Symbol.species]
返回值
呼叫 get [Symbol.species] 時,建構函式 (this) 的值。返回值用於從構建新 Promise 的 Promise 鏈式方法(promise chaining methods)構建返回值。
描述
[Symbol.species] 訪問器屬性返回 Promise 物件的預設建構函式。子類建構函式可以重寫它以更改建構函式分配。預設實現基本上是
// Hypothetical underlying implementation for illustration
class Promise {
static get [Symbol.species]() {
return this;
}
}
由於這種多型實現,派生子類的 [Symbol.species] 預設情況下也將返回建構函式本身。
class SubPromise extends Promise {}
SubPromise[Symbol.species] === SubPromise; // true
Promise 鏈式方法 — then()、catch() 和 finally() — 會返回新的 Promise 物件。它們透過 this.constructor[Symbol.species] 獲取用於構造新 Promise 的建構函式。如果 this.constructor 是 undefined,或者 this.constructor[Symbol.species] 是 undefined 或 null,則使用預設的 Promise() 建構函式。否則,將使用 this.constructor[Symbol.species] 返回的建構函式來構造新的 Promise 物件。
示例
普通物件中的 species
Symbol.species 屬性返回預設建構函式,即 Promise 的 Promise 建構函式。
Promise[Symbol.species]; // [Function: Promise]
派生物件中的 species
在自定義 Promise 子類的例項中,例如 MyPromise,MyPromise 的 species 是 MyPromise 建構函式。但是,您可能希望重寫它,以便在派生類的方法中返回父 Promise 物件。
class MyPromise extends Promise {
// Override MyPromise species to the parent Promise constructor
static get [Symbol.species]() {
return Promise;
}
}
預設情況下,Promise 方法將返回子類型別的 Promise。
class MyPromise extends Promise {
someValue = 1;
}
console.log(MyPromise.resolve(1).then(() => {}).someValue); // 1
透過重寫 [Symbol.species],Promise 方法將返回基礎 Promise 型別。
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% |
瀏覽器相容性
載入中…