gpt4 book ai didi

inheritance - Backbone View 继承-调用父级导致递归

转载 作者:行者123 更新时间:2023-12-04 10:19:06 24 4
gpt4 key购买 nike

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

最佳答案

正如 Model.extend 上的文档中所述,

Brief aside on super: JavaScript does not provide a simple way to call super — the function of the same name defined higher on the prototype chain. If you override a core function like set, or save, and you want to invoke the parent object's implementation, you'll have to explicitly call it, along these lines:



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

如果您愿意,也可以调用原型(prototype)链上的方法( 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有关该主题的更多信息。

关于inheritance - Backbone View 继承-调用父级导致递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com