Subclassing Your Own Objects

I want to create my own subclass of RegExp with additional methods. This is the most simplified version of my approach:

// Declare the subclass
function subRegExp(){}

// Inherit from the parent class
subRegExp.prototype = new RegExp();

// Create a new instance
regex = new subRegExp('[a-z]', 'g');

But I can not create a new instance.

It is reported that ECMAScript does not support subclassing of its own objects, but 5 years have passed, so I hope there are some options now.

How can i achieve this?

EDIT: is this normal or am I going to run into some problems?

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');
+4
source share
4 answers

Wrappers are your friend and common solution for providing advanced functionality without using inheritance.

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

, .

, , -. , RegExp ( Javascript ) .

+1

I tried this:

// 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 );

Conclusion:

true
function compile() { [native code] }
+1
source

Yes, it is now possible in ES6:

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

We have a test for it in the ES6 compatibility table, where you can see which implementations support it .

I will try to update the blog post soon that the subclass is Array in ES5 .

0
source

All Articles