I am having a problem creating new instances of an object.
Using the below code I was expecting each element to have it’s own random value (which is happening).
But then I was also expecting the this.element value to be contained to each instance of the object, but instead every time the value is changed in any instance of the object it is updating in all of them.
var Instance = function(element) {
this.$element = $(element);
this.subInstance.parent = this;
}
Instance.prototype = {
subInstance: {
parent: null,
$element: null,
init: function() {
var $this = this;
this.$element = this.parent.$element;
//test for what this.$element refers to in init function
var random = Math.random();
$('.element', this.$element).text('Updated ' + random);
//test for what this.$element refers to in an event handler
$('.element', this.$element).on('click', function(e) {
$this.$element.css('background-color', '#f00');
});
}
}
}
$('div.instance').each(function(i, o) {
var instance = new Instance(o);
instance.subInstance.init();
});
Now I know I could move subInstance out of the prototype and into the constructor using this.subInstance = {... but that seems wrong, why is this.$element not contained to each instance of the object?
JSFiddle of both examples: http://jsfiddle.net/q7zAg/
It may seem wrong, but it’s not. If each object created from the constructor needs to work with a unique
subInstance, you’ll need to create a new one for each individual instance. On theprototypeit will be shared.However, one thing you could do would be to use
Object.createto create a new instance that inherits from the prototypedsubInstance. Then you get the benefit of some reuse, and each instance can modify its own object.Now some may argue that the
subInstancestill shouldn’t be on theprototype, but rather should be a local variable in an IIFE. I would tend to agree with this.Here’s an example: