Symbol.species

Baseline 已廣泛支援

此特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 ⁨2016 年 9 月⁩以來,它已在各大瀏覽器中可用。

Symbol.species 靜態資料屬性代表 知名 Symbol Symbol.species。建立物件副本的方法可能會在物件上查詢此 Symbol,以便在建立副本時使用建構函式。

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

試一試

class Array1 extends Array {
  static get [Symbol.species]() {
    return Array;
  }
}

const a = new Array1(1, 2, 3);
const mapped = a.map((x) => x * x);

console.log(mapped instanceof Array1);
// Expected output: false

console.log(mapped instanceof Array);
// Expected output: true

知名 Symbol Symbol.species

Symbol.species 的屬性特性
可寫
可列舉
可配置

描述

[Symbol.species] 訪問器屬性允許子類覆蓋物件的預設建構函式。它指定了一個關於例項如何被複制的協議。例如,當您使用陣列的複製方法(如 map())時,map() 方法會使用 instance.constructor[Symbol.species] 來獲取用於構造新陣列的建構函式。有關更多資訊,請參閱 子類化內建物件

所有內建的 [Symbol.species] 實現都會返回 this 值,即當前例項的建構函式。這使得複製方法可以建立派生類(而不是基類)的例項——例如,map() 將返回與原始陣列型別相同的陣列。

示例

使用 species

在您的派生陣列類 MyArray 中,您可能希望返回 Array 物件。例如,在使用返回預設建構函式的 map() 等方法時,您希望這些方法返回一個父 Array 物件,而不是 MyArray 物件。species Symbol 可以讓您做到這一點。

js
class MyArray extends Array {
  // Overwrite species to the parent Array constructor
  static get [Symbol.species]() {
    return Array;
  }
}
const a = new MyArray(1, 2, 3);
const mapped = a.map((x) => x * x);

console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true

規範

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

瀏覽器相容性

另見