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
(親にのみ存在する) in を呼び出すことができます。これは insetRuleFailed
のバージョンを呼び出す必要があり、ForumFilterTest
それがオーバーライドするクラスを呼び出します。したがって、その名前が示すように、テスト目的で親に動作を追加しようとしているので、もちろん、親メソッドがForumFilter
独自にインスタンス化されている場合に使用する必要があります。