子类化本机对象

时间:2015-07-12 00:51:28

标签: javascript oop subclass

我想用其他方法创建自己的RegExp子类。这是我的方法的最简化版本:

c.save()

但我无法创建新实例。

This告诉我ECMAScript不支持本机对象的子类化,但它已经用了5年,所以我希望现在有一些选择。

我怎样才能做到这一点?

编辑:这样可以,还是会遇到一些问题?

// Declare the subclass
function subRegExp(){}

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

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

4 个答案:

答案 0 :(得分:2)

Wrappers是您的朋友,是提供扩展功能而不使用继承的常用解决方案。

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继承。根据我的经验,包装器比基于继承的扩展更容易测试和维护。

答案 1 :(得分:1)

恐怕还是没有。

但是,您可以使用自定义包装器对象类来模拟某些所需的功能。在构造函数中使用封装为它提供一个RegExp对象(Javascript最接近的)私有字段。

答案 2 :(得分: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] }

答案 3 :(得分:0)

是的,现在可以在ES6中使用:

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

我们在ES6 compat表中对它进行了测试,您可以在其中看到which implementations support it

我会尽快更新关于Array subclassing in ES5的博文(您引用的)。