/ /ネイティブオブジェクトのサブクラス化-javascript、oop、subclass

ネイティブオブジェクトのサブクラス化 - javascript、oop、サブクラス

追加のメソッドを使用して、独自の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");

回答:

回答№1は2

ラッパーは友人であり、継承を使用せずに拡張機能を提供する一般的なソリューションです。

var MyRegexClass = function(regExpInstance) {
this.originalRegex = regExpInstance;
};

// Replicate some of the native RegExp methods in your wrapper if you need them.
MyRegexClass.prototype.test = function(str) {
return this.originalRegex.test(str);
};

MyRegexClass.prototype.exec = function (str) {
return this.originalRegex.exec(str);
};

// Now add in your own methods.
MyRegexClass.prototype.myCustomFunction0 = function () {
// this method does something with this.originalRegex
};
MyRegexClass.prototype.myCustomFunction1 = function () {
// this method also does something with this.originalRegex
};

// Example usage
var matchDavids = new MyRegexClass(/David/);

// this call works, because my class provides the .test() method.
var hasMatch = matchDavids.test("David walked his dog to the park.");

// this call does not work, because my class does not expose the .compile() method.
matchDavids.compile();
// I would need to provide a .compile() method on MyRegexClass that calls to
// the originalRegex.compile().

はい、継承チェーンを失います。 MyRegexClass ネイティブRegExpを継承しません。私の経験では、ラッパーは継承ベースの拡張よりもテストと保守が簡単です。


回答№2の場合は1

ただし、一部をシミュレートできる場合がありますカスタムラッパーオブジェクトクラスを使用して必要な機能。コンストラクターでカプセル化を使用して、RegExpオブジェクトをプライベートフィールド(Javascriptに最も近いもの)として指定します。


回答№3の場合は1

私はこれを試した:

// Declare the subclass
function subRegExp(){}
// make your object inherit from regex object
subRegExp.prototype = Object.create( RegExp.prototype );

var x = new subRegExp();
// see if your custom object inherited the RegExp properties/functions/methods
console.dir( "compile" in x );
console.dir( x.compile );

出力:

true
function compile() { [native code] }

回答№4の場合は0

はい、ES6で可能になりました。

class R extends RegExp {}
var r = new R("baz", "g");
return r.exec("foobarbaz")[0] === "baz" && r.lastIndex === 9;

ES6互換表にテストがあり、そこで見ることができます サポートする実装.

ブログの投稿(参照した)を更新しよう ES5の配列サブクラス化 そのうち。