我有一个 JavaScript 类,我想通过创建一个子类来覆盖父方法。但是,我正在努力研究如何从父上下文中调用子方法。
这是我父母的精简版:
// "rules" is a global hash
function ForumFilter() {
this.scanText = function(title, body) {
// Save 'this' context, as each() overwrites it
var that = this;
// This is jQuery each()
$.each(rules, function(ruleName, rule) {
// rule.search is a regex
var match = rule.search.test(body);
if (match)
{
that.isPassed = false;
// ** I'd like to call a child method here,
// ** but it only calls the method in this class
that.setRuleFailed(ruleName);
}
});
}
this.setRuleFailed = function(ruleName) {
this.failedRules.push(ruleName);
}
}
这是我对孩子的尝试:
ForumFilterTest.prototype = new ForumFilter();
ForumFilterTest.prototype.setRuleFailed = function(ruleName) {
// Call parent
ForumFilter.setRuleFailed(ruleName);
// Record that this one has triggered
this.triggered.push(ruleName);
}
这是我从子实例调用我的父方法:
var scanner = new ForumFilterTest();
scanner.scanText("Hello", "Hello");
因此, in scanText
(仅存在于父级中)它可能会调用setRuleFailed
,这应该调用版本 in ForumFilterTest
,而版本又会调用它覆盖的类。因此,正如它的名字所暗示的那样,我试图向父级添加一个行为以进行测试,所以我当然希望ForumFilter
在它自己实例化的情况下使用父方法。