var TestView = Backbone.View.extend({
options: {
"theList": []
},
initialize: function() {
console.log(this.options.theList.length);
this.options.theList.push("xxx");
}
});
// other place:
var view1 = new TestView();
// the console result will be 0
var view2 = new TestView();
// the console result will be 1 !!!
var view3 = new TestView();
// the console result will be 2 !!!!!!
...
为什么呢?我认为每次new
TestView
!
答案 0 :(得分:2)
extend
调用中的所有内容都将附加到视图的原型中。这意味着options
所有TestView
的所有实例都会共享您的this.options.theList.push("xxx");
,所以每次:
options
您正在将字符串推送到所有实例通过原型共享/引用的完全相同的数组。
如果你想为每个实例单独var TestView = Backbone.View.extend({
initialize: function() {
this.options.theList = [ ];
console.log(this.options.theList.length);
this.options.theList.push("xxx");
}
});
,请在视图的构造函数中设置它:
{{1}}