Eri*_*rik 7 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);
}
});
Run Code Online (Sandbox Code Playgroud)
当我尝试创建nestedNestedChildView时:
var t = new nestedNestedChildView();
Run Code Online (Sandbox Code Playgroud)
我得到无限递归:这是jsfiddle
nik*_*shr 14
正如Model.extend上的文档中所述,
简要介绍一下super:JavaScript没有提供一种调用super的简单方法 - 在原型链上定义的同名函数更高.如果覆盖像set或save这样的核心函数,并且想要调用父对象的实现,则必须按以下方式显式调用它:
在类层次结构中,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);
}
});
Run Code Online (Sandbox Code Playgroud)
或者如果您愿意,可以调用原型链上的方法(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);
}
});
Run Code Online (Sandbox Code Playgroud)