2

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独自にインスタンス化されている場合に使用する必要があります。

4

1 に答える 1

3

問題をよりよく理解した後、実際に提案された変更を次に示します。ForumFilter具体的には、メソッドをそのに移動する必要がありますprototype。これにより、ForumFilterTestメソッドがメソッドを明示的に参照できるようになりForumFilterます。

ステップ 1:ForumFilterメソッドをその に移動しますprototype

function ForumFilter() {}
ForumFilter.prototype.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);
        }
    });
};
ForumFilter.prototype.setRuleFailed = function(ruleName) {
    this.failedRules.push(ruleName);
};

ステップ 2:ForumFilter必要に応じて「親」メソッドを明示的に参照します。

// "child class" implementation
function ForumFilterTest() {}
ForumFilterTest.prototype = new ForumFilter();
ForumFilterTest.prototype.setRuleFailed = function(ruleName) {
    // Call parent
    ForumFilter.prototype.setRuleFailed.call(this, ruleName);
    // Record that this one has triggered
    this.triggered.push(ruleName);
};
于 2013-04-01T13:53:34.637 に答える