The well-known symbol
Symbol.species
specifies a function-valued property that the constructor function uses to create derived objects.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
The species accessor property allows subclasses to override the default constructor for objects.
特性属性在
Symbol.species
|
|
|---|---|
| 可写 | no |
| 可枚举 | no |
| 可配置 | no |
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:
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
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Symbol.species' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
species
|
Chrome 51 | Edge 13 | Firefox 41 | IE No | Opera 38 | Safari 10 | WebView Android 51 | Chrome Android 51 | Firefox Android 41 | Opera Android 41 | Safari iOS 10 | Samsung Internet Android 5.0 |
nodejs
6.5.0
|
完整支持
不支持
用户必须明确启用此特征。
Symbol
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()