Symbol.species
Symbol.species
Symbol.species
是指定一个构造函数创建派生对象的函数值属性。
| Symbol.species
属性的属性特性: |
|:----|
| Writable | no |
| Enumerable | no |
| Configurable | no |
描述
species 访问器属性允许子类覆盖对象的默认构造函数。
示例
您可能想要返回Array
派生数组类中的对象MyArray
。例如,当使用诸如map()
返回默认构造函数的方法时,您希望这些方法返回父Array
对象而不是MyArray
对象。物种符号可以让你做到这一点:
class MyArray extends Array {
// Overwrite species to the parent Array constructor
static get [Symbol.species]() { return Array; }
}
var a = new MyArray(1,2,3
var mapped = a.map(x => x * x
console.log(mapped instanceof MyArray // false
console.log(mapped instanceof Array // true
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Symbol.species' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262)The definition of 'Symbol.species' in that specification. | Living Standard | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer/Edge | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 51 | (Yes) | 41 (41) | 14 | 38 | 10 |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE/Edge Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | No support | 5 | (Yes) | 41.0 (41) | 14 | 38 | 10 |