好的,我最近遇到了这个问题,我不太明白为什么会这样。有人可以解释为什么this._views
会“异花授粉”吗?代码如下:
var layout = Backbone.View.extend({
_views: [],
addToViews: function(view) {
this._views.push(view);
},
renderViews: function() {
console.log(this._views);
}
});
var view1 = new layout();
view1.addToViews('some view');
view1.renderViews(); //outputs array(1)['some view']
var view2 = new layout();
view2.renderViews(); //outputs array(1)['some view'] **incorrect!**
这工作正常:
var layout = Backbone.View.extend({
//_views: [],
addToViews: function(view) {
this._views = this._views || [];
this._views.push(view);
},
renderViews: function() {
console.log(this._views);
}
});
var view1 = new layout();
view1.addToViews('some view');
view1.renderViews(); //outputs array(1)['some view']
var view2 = new layout();
view2.renderViews(); //outputs undefined **correct**
普通的香草 js 实现似乎也可以正常工作
var layout = function() {
var _views = [];
return {
addToViews: function(view) {
_views.push(view);
},
renderViews: function() {
console.log(_views);
}
}
};
var view1 = new layout();
view1.addToViews('some view');
view1.renderViews(); //outputs array(1)['some view']
var view2 = new layout();
view2.renderViews(); //outputs array(0)[]
那么为什么this._views
当我们创建一个全新的实例时保存状态呢?