RegExp[Symbol.species]

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

RegExp[Symbol.species] 静态访问器属性返回在某些 RegExp 方法中用于构造已复制的正则表达式的构造函数。

警告: [Symbol.species] 的存在允许执行任意代码,并可能产生安全漏洞。它还会使某些优化变得更加困难。引擎实现者正在 调查是否要移除此功能。如果可能,请避免依赖它。

语法

js
RegExp[Symbol.species]

返回值

调用 get [Symbol.species] 时构造函数 (this) 的值。返回值用于构造已复制的 RegExp 实例。

描述

[Symbol.species] 访问器属性返回 RegExp 对象的默认构造函数。子类构造函数可以覆盖它以更改构造函数分配。默认实现基本上是

js
// Hypothetical underlying implementation for illustration
class RegExp {
  static get [Symbol.species]() {
    return this;
  }
}

由于这种多态实现,派生子类的 [Symbol.species] 默认情况下也将返回构造函数本身。

js
class SubRegExp extends RegExp {}
SubRegExp[Symbol.species] === SubRegExp; // true

某些 RegExp 方法会在运行 exec() 之前创建当前正则表达式实例的副本,以避免保留副作用,例如对 lastIndex 的更改。[Symbol.species] 属性用于确定新实例的构造函数。复制当前正则表达式实例的方法是

示例

普通对象中的 species

[Symbol.species] 属性返回默认构造函数,即 RegExp 对象的 RegExp 构造函数。

js
RegExp[Symbol.species]; // function RegExp()

派生对象中的 species

在自定义 RegExp 子类的实例中,例如 MyRegExpMyRegExp 的 species 是 MyRegExp 构造函数。但是,您可能希望覆盖它,以便在派生类方法中返回父 RegExp 对象。

js
class MyRegExp extends RegExp {
  // Overwrite MyRegExp species to the parent RegExp constructor
  static get [Symbol.species]() {
    return RegExp;
  }
}

或者,您可以使用此方法来观察复制过程。

js
class MyRegExp extends RegExp {
  constructor(...args) {
    console.log("Creating a new MyRegExp instance with args:", args);
    super(...args);
  }
  static get [Symbol.species]() {
    console.log("Copying MyRegExp");
    return this;
  }
  exec(value) {
    console.log("Executing with lastIndex:", this.lastIndex);
    return super.exec(value);
  }
}

Array.from("aabbccdd".matchAll(new MyRegExp("[ac]", "g")));
// Creating a new MyRegExp instance with args: [ '[ac]', 'g' ]
// Copying MyRegExp
// Creating a new MyRegExp instance with args: [ MyRegExp /[ac]/g, 'g' ]
// Executing with lastIndex: 0
// Executing with lastIndex: 1
// Executing with lastIndex: 2
// Executing with lastIndex: 5
// Executing with lastIndex: 6

规范

规范
ECMAScript® 2026 语言规范
# sec-get-regexp-%symbol.species%

浏览器兼容性

另见