I’m trying to create multiple instances of a JavaScript “class” or object but it seems to be acting as a singleton… Could someone assist me with the following code?
(function() {
/*
* Canvas object
*/
var Canvas = function( el ) {
_self = this;
_self.el = el;
}
Canvas.prototype.init = function() {
_self.el.style.backgroundColor = "#000";
_self.el.addEventListener( "mousedown", _self.onMouseDown );
}
Canvas.prototype.onMouseDown = function() {
console.log( 'onMouseDown: ', _self.el );
}
var cOne = new Canvas( document.getElementById('one') );
var cTwo = new Canvas( document.getElementById('two') );
cOne.init();
cTwo.init();
})();
When not using
varon a variable declaration, it becomes a global variable. So when you create a new instance, it updates the global variable.An alternative to this approach is to simple make a
elan object property:jsFiddle Demo
Moreover, you should consider binding your
.onMouseDownmethod to the current object. Use this instead:or this: