I had a problem creating new instances of the object.
Using the code below, I expected each element to have its own random value (what happens).
But then I also expected that the value of this.element would be contained in every instance of the object, but instead, every time the value changes in any instance of the object, it is updated 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 that I can move subInstance from the prototype and into the constructor using this.subInstance = {... , but this seems wrong, why is this.$element not contained in every instance of the object?
JS A note of both examples: http://jsfiddle.net/q7zAg/
source share