Inheritance in JavaScript is prototypical - objects can refer directly to properties higher up in the prototype chain.
In your example, one
and two
both share a common prototype, and do not provide their own values for myProperty
so they both refer directly to Model.protoype.myProperty
.
You should create new myProperty
array for each model you instantiate. Model.initialize
is the idiomatic place for this kind of initialisation - overriding constructor
is unnecessarily complex.
var Model = Backbone.Model.extend({
initialize: function() {
this.myProperty = [];
}
});
Alternatively you could make myProperty
as an attribute of the model:
var Model = Backbone.Model.extend({
defaults: function() {
return {
myProperty: []
}
}
});
It is important to note that defaults
is a function - if you were to use a simple object you would encounter the same shared reference issue.