我创建了一个类,使用它可以在正则表达式对象 ( 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);
...
编辑: 感谢 T.J. 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
当我从 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"
或者,您可以通过简单地添加到 RegExp.prototype
来扩充内置的 RegExp
类型:
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"
请注意,扩展内置原型(prototype)是有争议的,至少有两个阵营,一个说“永远不要那样做,你会遇到麻烦”,另一个说“这就是原型(prototype)的用途”。从务实的 Angular 来看,请注意命名冲突——其他代码也扩展了 native 原型(prototype),并且随着语言及其运行时的发展, future 会添加到基本类型。
关于javascript - 如何扩展正则表达式对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178607/