My Backbone应用程序有一个带有静态属性的父类,以及两个子类。我试图从子类修改父的静态属性,但这似乎不起作用。以下是一些示例代码:
var ParentView = Backbone.View.extend({}, {
staticProperty: 1,
getStaticProperty: function() {
return this.staticProperty;
},
setStaticProperty: function(value) {
this.staticProperty = value;
}
});
console.log('ParentView.staticProperty: ' + ParentView.getStaticProperty());
ParentView.setStaticProperty(2);
var ChildView1 = ParentView.extend({
initialize: function() {
console.log('ChildView1.staticProperty: ' + ChildView1.getStaticProperty());
ChildView1.setStaticProperty(3); // THIS SEEMS TO DO NOTHING
}
});
var ChildView2 = ParentView.extend({
initialize: function() {
console.log('ChildView2.staticProperty: ' + ChildView2.getStaticProperty());
}
});
var testView1 = new ChildView1();
var testView2 = new ChildView2();
这是一个jsfiddle:http://jsfiddle.net/2agTW/1/
我希望得到以下结果:
ParentView.staticProperty: 1
ChildView1.staticProperty: 2
ChildView2.staticProperty: 3
但相反,我得到了:
ParentView.staticProperty: 1
ChildView1.staticProperty: 2
ChildView2.staticProperty: 2 // I THINK THIS SHOULD BE 3
知道为什么吗?
答案 0 :(得分:1)
您应该使用`ParentView'代替:
var ParentView = Backbone.View.extend({}, {
staticProperty: 1,
getStaticProperty: function() {
return ParentView.staticProperty;
},
setStaticProperty: function(value) {
ParentView.staticProperty = value;
}
});
我认为Backbone的继承模型可能有点嘎嘎(技术术语)。或者至少,它不具有传统意义上的继承。在所谓的“静态”属性的情况下,extend函数最终将所有属性(实例和静态)复制到子节点,因此,ChildView1
和ChildView2
每个都有自己的{{{ 1}}。当您在staticProperty
中致电setStaticProperty
时,它会在ChildView1
的上下文中运行,使其中ChildView1
运算符的功能副本指向this
。< / p>
我不会说教程本身是错误的 - 如果你没有使用继承,ChildView1.staticProperty
会起作用,但它肯定会产生误导(我怀疑作者使用CoffeeScript会将这个特殊问题隐藏起来)。如果您希望所有实例引用相同的属性,我总是引用基类并避免使用this
属性。
这篇文章帮助我理解了Backbone的继承怪癖 - 这绝对值得一读。 http://www.erichynds.com/blog/backbone-and-inheritance