JavaScript - Symbol.species 属性
为了指示应使用哪个构造函数来创建派生对象,JavaScript 提供了一个名为 Symbol.species 的独特属性。在创建类或对象的新实例时,此符号在类或对象原型中用作键,以标识要使用的构造函数。
Symbol.species 属性允许用户指定应使用哪个构造函数来创建类或子类的新实例。
语法
以下是 JavaScript Symbol.species 属性的语法 -
[Symbol.species]
参数
species 访问器属性用于允许子类覆盖默认构造函数。
返回值
此属性返回一个派生对象。
示例
示例 1
让我们看下面的示例,其中将要使用 map() 方法。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x extends Array {
static get[Symbol.species]() {
return Array;
}
}
const a = new x(11, 2, 33);
const b = a.map(x => x * 2);
document.write(b instanceof x, " < br > ");
document.write(b instanceof Array);
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑以下示例,我们将使用 slice() 方法。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x extends Uint8Array {
static get[Symbol.species]() {
return Uint8Array;
}
}
const a = new x([11, 22, 33, 44]);
const b = a.slice(1, 2);
document.write(b instanceof x, " < br > ");
document.write(b instanceof Uint8Array);
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将创建一个子类,并在子类实例上使用 then() 方法。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x extends Promise {
static get[Symbol.species]() {
return Promise;
}
}
const a = new x((resolve, reject) => {
resolve('welcome');
});
const b = a.then(result => result.toUpperCase());
document.write(b instanceof x, " < br > ");
document.write(b instanceof Promise);
</script>
</body>
</html>
当我们执行脚本时,它将在网页上显示一段文本。

