2
我有一个JavaScript类,我想通过创建一个子类来重写父级方法。但是,我正在努力研究如何从父级上下文中调用子级方法。在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");
因此,在scanText
(它只存在于父项中)可能会调用setRuleFailed
,它应该调用ForumFilterTest
中的版本,该版本又调用它覆盖的类。因此,正如它的名字所暗示的那样,我试图向父级添加一个行为用于测试目的,所以当然我想要使用父级方法,如果ForumFilter
是自己实例化的。
感谢您的帮助,非常赞赏的jsfiddle例子。这几乎是我的目标,但我希望孩子能够调用父母,[按此](http://jsfiddle.net/Tsmgg/2/)。因此,它添加到父项而不是替换它。 – halfer
啊,你需要将父方法移动到原型,以便子类重新调用“覆盖”的方法。看到这个:http://jsfiddle.net/Tsmgg/3/ – jmar777
我刚刚更新我的答案,希望更适用。 – jmar777