Symbol.species
ウェルノウンシンボルの Symbol.species は、コンストラクター関数が派生オブジェクトを生成する際に使用する関数値プロパティを指定します。
試してみましょう
解説
species アクセサープロパティを使用すると、オブジェクトの生成に使われるデフォルトコンストラクターを上書きすることができます。
Symbol.species のプロパティ属性 |
|
|---|---|
| 書込可能 | 不可 |
| 列挙可能 | 不可 |
| 設定可能 | 不可 |
例
species の使用
Array オブジェクトを派生した配列クラス MyArray で返したいことがあるでしょう。例えば、デフォルトのコンストラクターを返す map() のようなメソッドを使用している場合、これらのメソッドは MyArray オブジェクトではなく親の Array オブジェクトを返したいとします。 species シンボルでこれを実現することができます。
js
class MyArray extends Array {
// Overwrite species to the parent Array constructor
static get [Symbol.species]() { return Array; }
}
let a = new MyArray(1,2,3);
let mapped = a.map(x => x * x);
console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true
仕様書
| Specification |
|---|
| ECMAScript Language Specification # sec-symbol.species |
ブラウザーの互換性
BCD tables only load in the browser