Mat*_*att 11 javascript prototypal-inheritance backbone.js
在过去的两天里,我一直在敲打这个.由于某种原因,骨干是在继承的子模型之间共享父实例数据.下面是一个例子:
var Base = Backbone.Model.extend({
index : []
});
var Group = Base.extend({
initialize : function() {
this.index.push('from group');
}
});
var User = Base.extend({
initialize : function() {
this.index.push('from user');
}
});
var user = new User();
console.log(user.index); // ['from user']
var group = new Group();
console.log(group.index) // ['from user', 'from group']
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是:
console.log(user.index); // ['from user']
console.log(group.index) // ['from group']
Run Code Online (Sandbox Code Playgroud)
任何见解?
谢谢!马特
Sky*_*son 14
您所经历的实质上是JS通过引用而不是通过值传递对象(或数组)的方式的副产品.如果希望用户和组的索引不同,只需在初始化函数中将其实例化为数组.
var Base = Backbone.Model.extend({
initialize: function() {
this.index = [];
}
});
Run Code Online (Sandbox Code Playgroud)
索引成员就像一个类变量,因为它位于Base的原型链中,因此所有实例共享它,就像它包含的方法一样.尝试切换实例化用户和组的顺序.现在索引包含什么?它反过来了吗?那是因为他们正在共享对象传递的所有内容.
为了使它成为实例变量,您需要在Base的构造函数中实例化它,并让每个子类从它们各自的构造函数中调用该构造函数.喜欢:
var Base = Backbone.Model.extend({
initialize: function() {
this.index = [];
}
});
var User = Base.extend({
initialize: function() {
Base.prototype.initialize.call( this );
this.index.push('User');
}
});
// repeat it for group.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3188 次 |
| 最近记录: |