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");

因此, in scanText(仅存在于父级中)它可能会调用setRuleFailed,这应该调用版本 in 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 回答