Symbol.species

Symbol.species 静态数据属性代表 众所周知的符号 @@species。创建对象副本的方法可以在对象上查找此符号,以便构造函数在创建副本时使用。

¥The Symbol.species static data property represents the well-known symbol @@species. Methods that create copies of an object may look up this symbol on the object for the constructor function to use when creating the copy.

警告:@@species 的存在允许执行任意代码并可能产生安全漏洞。它还使某些优化变得更加困难。引擎实现者是 研究是否删除此功能。如果可能的话,避免依赖它。

¥Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

Try it

¥Value

众所周知的符号 @@species

¥The well-known symbol @@species.

Property attributes of Symbol.species
Writable no
Enumerable no
Configurable no

描述

¥Description

@@species 访问器属性允许子类覆盖对象的默认构造函数。这指定了有关如何复制实例的协议。例如,当你使用数组的复制方法时,例如 map()map() 方法使用 instance.constructor[Symbol.species] 来获取构造新数组的构造函数。欲了解更多信息,请参阅 子类化内置函数

¥The @@species accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as map(). the map() method uses instance.constructor[Symbol.species] to get the constructor for constructing the new array. For more information, see subclassing built-ins.

@@species 的所有内置实现都返回 this 值,该值是当前实例的构造函数。这允许复制方法来创建派生类而不是基类的实例 - 例如,map() 将返回与原始数组相同类型的数组。

¥All built-in implementations of @@species return the this value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, map() will return an array of the same type as the original array.

示例

¥Examples

使用品种

¥Using species

你可能希望在派生数组类 MyArray 中返回 Array 对象。例如,当使用 map() 等返回默认构造函数的方法时,你希望这些方法返回父 Array 对象,而不是 MyArray 对象。species 符号可让你执行此操作:

¥You might want to return Array objects in your derived array class MyArray. For example, when using methods such as map() that return the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The species symbol lets you do this:

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

规范

Specification
ECMAScript Language Specification
# sec-symbol.species

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看