在JavaScript中从父级调用子方法

时间:2013-04-01 13:48:58

标签: javascript inheritance prototypal-inheritance

我有一个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又会调用它覆盖的类。因此,正如其名称所暗示的,我正在尝试向父级添加一个行为以用于测试目的,因此当然我希望在{{1}}自己实例化时使用父方法。

1 个答案:

答案 0 :(得分: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“parent”方法:

// "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);
};
相关问题