我创建了一个类,可以使用它获取正则表达式对象中组的所有开始和结束位置(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 或另一个对象扩展时,一切都按预期工作。
您至少有几个选择。正如我所看到的,您正在使用 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)
请注意,扩展内置原型是有争议的,至少有两个阵营,一个阵营说“永远不要这样做,你会遇到麻烦”,另一个阵营说“这就是原型的用途”。从实用的角度来看,要小心命名冲突——其他代码也扩展了本机原型,并且随着语言及其运行时的发展,未来会对基本类型进行添加。