In trying to come up with a basic model to handle all the similar entities for the application domain I'm working on, I created:
- A basic object (Entity): that has some shared properties and initializers, setup as Prototype
- A product object (Product): that "inherits" from Entity. And contains a list of "Variants"
- A variant object (Variant): that "inherits" from Entity.
Product.prototype = new Entity();
Variant.prototype = new Entity();
When I run this, something weird happens: the "variants" list from the "product" object, ends up containing two elements, which is fine, but instead of these being two separates instances of "Variant", they point at the same memory space.
I've done some debugging (alert based), to ensure that, during the 'for loop' that fills the observableArray, things look fine.
var Product = function (data) {
var initial = data || {};
this.variants = ko.observableArray();
this.init(initial);
if (initial.variants != null) {
for (var i = 0; i < initial.variants.length; i++) {
// NOTE: this is the misterious line. Creating two instances
// of 'new Variant', ends up pushing a single instance.
this.variants.push(new Variant(initial.variants[i]));
//-----------------------------------------------------------
alert(this.variants()[i].name());
}
}
I asume I'm missing some Javascript basics to figure out what am I doing wrong.
Heres the complete sample at JsFiddle.