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