2013-04-01 41 views
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是自己实例化的。

回答

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); 
}; 
+0

感谢您的帮助,非常赞赏的jsfiddle例子。这几乎是我的目标,但我希望孩子能够调用父母,[按此](http://jsfiddle.net/Tsmgg/2/)。因此,它添加到父项而不是替换它。 – halfer

+0

啊,你需要将父方法移动到原型,以便子类重新调用“覆盖”的方法。看到这个:http://jsfiddle.net/Tsmgg/3/ – jmar777

+0

我刚刚更新我的答案,希望更适用。 – jmar777