2013-04-01 40 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