我希望创建一个自己的RegExp子类,并添加额外的方法。以下是我采用的最简化的方法:
// Declare the subclass
function subRegExp(){}
// Inherit from the parent class
subRegExp.prototype = new RegExp();
// Create a new instance
regex = new subRegExp('[a-z]', 'g');
但我无法创建一个新实例。
这篇文章告诉我ECMAScript不支持原生对象的子类化,但已经过去了5年,所以我希望现在有一些选项。
我该如何实现这个呢?
编辑:这样可以吗?还是会遇到问题?
function subRegExp(str, flags){
var instance = new RegExp(str, flags);
// Custom method
instance.setFlags = function(flags){
return new subRegExp(this.source, flags);
}
return instance;
}
regex = new subRegExp('[a-z]', 'g');