When I associate a structure with a function's prototype and then instantiate multiple objects with that function, they all share the same instance of the structure. I'd like for each object to have it's own instance of the structure without having to explicitly create a new instance when the objects are instantiated; is that possible?
Here's a condensed example of what I'm trying to do:
function defineClass(constructor, instanceMembers) {
constructor.prototype.model = instanceMembers.model;
return constructor;
}
var visualObject = defineClass(function () { }, {
model: {
setPosition: function (x, y) {
this.x = x;
this.y = y;
}
}
});
var testA = new visualObject();
var testB = new visualObject();
testA.model.setPosition(10, 10);
console.log(testB.model.x); // outputs "1", but want it to be undefined
That doesn't work, as testA.model and testB.model both reference the same entity.
If I instead clone the structure at the time of construction, then it works, but I'm really hoping to avoid that cloning operation. This code works but hurts me:
function defineClass(instanceMembers) {
var constructor = function () {
// Create a copy of the model member in this object instance
this.model = $.extend(true, {}, this.model);
};
constructor.prototype.model = instanceMembers.model;
return constructor;
}
var visualObject = defineClass({
model: {
setPosition: function (x, y) {
this.x = x;
this.y = y;
}
}
});
var testA = new visualObject();
var testB = new visualObject();
testA.model.setPosition(10, 10);
console.log(testB.model.x); // is undefined, as expected
Does javascript provide a way to do this without the need for the copy-on-instantiation?