gpt4 book ai didi

javascript - 子类化 native 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:44:47 25 4
gpt4 key购买 nike

我想用额外的方法创建我自己的 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');

最佳答案

包装器是您的 friend ,也是在不使用继承的情况下提供扩展功能的常用解决方案。

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

关于javascript - 子类化 native 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com