如何扩展正则表达式对象

vel*_*lop 3 javascript oop

我创建了一个类,可以使用它获取正则表达式对象中组的所有开始和结束位置(https://github.com/valorize/MultiRegExp2)。我想用这个新的“类”包装初始正则表达式并添加一个新方法execForAllGroups。我怎样才能做到这一点/覆盖旧的正则表达式但仍然使用它的所有功能,如搜索、测试等?

我有:

function MultiRegExp2(baseRegExp) {
    let filled = fillGroups(baseRegExp);
    this.regexp = filled.regexp;
    this.groupIndexMapper = filled.groupIndexMapper;
    this.previousGroupsForGroup = filled.previousGroupsForGroup;
}

MultiRegExp2.prototype = new RegExp();
MultiRegExp2.prototype.execForAllGroups = function(string) {
    let matches = RegExp.prototype.exec.call(this.regexp, string);
    ...
Run Code Online (Sandbox Code Playgroud)

编辑:感谢 TJ Crowder,我调整了 ES6 类语法并扩展了 RegExp:

class MultiRegExp extends RegExp {
    yourNiftyMethod() {
        console.log("This is your nifty method");
    }
}

But
let rex = new MultiRegExp(); // rex.constructor.name is RegExp not MultiRegExp
rex.yourNiftyMethod(); // returns: rex.yourNiftyMethod is not a function
Run Code Online (Sandbox Code Playgroud)

当我从 String 或另一个对象扩展时,一切都按预期工作。

T.J*_*der 5

您至少有几个选择。正如我所看到的,您正在使用 ES2015(又名 ES6)功能,最明显的事情就是扩展RegExp

class MultiRegExp2 extends RegExp {
  yourNiftyMethod() {
    console.log("This is your nifty method");
  }
}

let rex = new MultiRegExp2(/\w+/); // or   = new MultiRegExp2("\\w+");
console.log(rex.test("testing"));  // "true"
rex.yourNiftyMethod();             // "This is your nifty method"
Run Code Online (Sandbox Code Playgroud)

RegExp或者,您可以通过简单地添加以下内容来增强内置类型RegExp.prototype

RegExp.prototype.yourNiftyMethod = function() {
  console.log("This is your nifty method");
};

let rex = /\w+/;
console.log(rex.test("testing"));  // "true"
rex.yourNiftyMethod();             // "This is your nifty method"
Run Code Online (Sandbox Code Playgroud)

请注意,扩展内置原型是有争议的,至少有两个阵营,一个阵营说“永远不要这样做,你会遇到麻烦”,另一个阵营说“这就是原型的用途”。从实用的角度来看,要小心命名冲突——其他代码也扩展了本机原型,并且随着语言及其运行时的发展,未来会对基本类型进行添加。

  • @velop:也许,或者也许这是不成熟的微优化。:-) 不过,这篇文章很有趣。如果需要超强性能,一旦 Chrome 57 发布,您可能会想同时测试它。([此页面](https://en.wikipedia.org/wiki/Google_Chrome_version_history)表明Chrome Canary可能已经在使用该版本的V8。) (2认同)