Backbone View继承 - 调用parent导致递归

时间:2013-04-13 11:51:40

标签: inheritance backbone.js backbone-views

我有三个Backbone 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

1 个答案:

答案 0 :(得分:14)

Model.extend上的文档中所述,

  

简要介绍一下super:JavaScript没有提供一种简单的调用方式   super - 在原型上定义更高的同名函数   链。如果你覆盖核心功能,比如set,或者你想要保存   要调用父对象的实现,你必须这样做   明确地称它为:

在您的类层次结构中,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