我想用其他方法創建自己的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');
但我無法創建一個新的實例。
This告訴我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');
我用你的想法編輯了我的問題,我錯過了什麼嗎? – notyourtype
如果你這樣做,你必須省略'new'關鍵字。 – SuperJedi224
@notyourtype使用你的新代碼,你實際上並沒有創建一個子類。 'regex instanceof subRegExp'將是'false'。你只是創建一個替代構造函數。 (事實上,你用'new'調用它實際上是不相關的,如果它返回一個Object而不是'this'。) –