2013-04-13 42 views
7

我有三大骨幹View類繼承:骨幹觀的繼承 - 調用父導致遞歸

var preventRecursion = 0; 

var parentView = Backbone.View.extend({ 

    initialize: function(){ 
    console.log('parentView'); 
    } 
}); 

var nestedChildView = parentView.extend({ 

    initialize: function(){ 

    if (++preventRecursion == 5) {throw "Recursion"}; 

    console.log('nestedChildView'); 
    this.constructor.__super__.initialize.apply(this);   
    } 
}); 

var nestedNestedChildView = nestedChildView.extend({ 

    initialize: function(){ 
    console.log('nestedNestedChildView'); 
    this.constructor.__super__.initialize.apply(this);   
    } 
}); 

當我嘗試創建nestedNestedChildView:

var t = new nestedNestedChildView(); 

我得到無限遞歸: 這裏是jsfiddle

回答

13

正如Model.extend的文檔所述,

超級簡介:JavaScript不提供簡單的方法來調用 超級 - 在原型 鏈上定義更高的同名函數。如果重寫等設定的核心功能,或保存,並且要 調用父對象的實現,你必須 顯式調用它,沿着這些路線:

在你的類層次結構,this.constructor總是等於nestedNestedChildView的構造函數,這意味着this.constructor.__super__.initialize將是nestedChildView.initialize,因此是一個循環。請參閱http://jsfiddle.net/X5yBb/進行測試。

你可以顯式調用類__super__(http://jsfiddle.net/X5yBb/1/

var nestedChildView = parentView.extend({ 
    initialize: function(){ 
    console.log('nestedChildView'); 
    nestedChildView.__super__.initialize.apply(this);   
    } 
}); 

var nestedNestedChildView = nestedChildView.extend({ 
    initialize: function(){ 
    console.log('nestedNestedChildView'); 
    nestedNestedChildView.__super__.initialize.apply(this);   
    } 
}); 

,或者如果你喜歡調用的方法的原型鏈(http://jsfiddle.net/X5yBb/2/):

var nestedChildView = parentView.extend({ 
    initialize: function(){ 
    console.log('nestedChildView'); 
    parentView.prototype.initialize.apply(this);   
    } 
}); 

var nestedNestedChildView = nestedChildView.extend({ 
    initialize: function(){ 
    console.log('nestedNestedChildView'); 
    nestedChildView.prototype.initialize.apply(this);   
    } 
}); 

進一步的信息請參見Accessing parent class in BackboneSuper in Backbone就此主題而言。

+0

謝謝你的回答。 – Erik