骨干

2013-05-30 135 views
1
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 !!!!!! 

...骨干

为什么视野中的其他附加变量?我认为它会每次只是我0 newTestView

回答

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"); 
    } 
}); 
+0

相当不错,我真的很感谢你的回答! – Liber

+0

但我在Chrome中控制视图,'option'属性不放置在__proto__属性中,它只是在那里。 – Liber

+0

@Liber:你看错了地方:http://jsfiddle.net/ambiguous/T24Rz/ –