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();
})();
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();
})();
Share
Improve this question
asked Feb 7, 2013 at 1:41
user1960364user1960364
2,0196 gold badges29 silver badges48 bronze badges
2
- How is it acting as a singleton? May we see your HTML. Create a fiddle perhaps. – Aadit M Shah Commented Feb 7, 2013 at 1:45
- nothing obviously wrong. Please explain what behavior you're seeing thats incorrect. – Ben McCormick Commented Feb 7, 2013 at 1:45
2 Answers
Reset to default 4When not using var
on a variable declaration, it bees 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 el
an object property:
var Canvas = function(el) {
this.el = el;
};
jsFiddle Demo
Moreover, you should consider binding your .onMouseDown
method to the current object. Use this instead:
this.el.addEventListener(..., this.onMouseDown.bind(this));
or this:
Canvas.prototype.init = function() {
var self = this;
...
this.el.addEventListener(..., function() {
self.onMouseDown.call(self);
});
};
var Canvas = function( el ) {
var _self = this;
_self.el = el;
}
Canvas.prototype.init = function() {
this.el.style.backgroundColor = "#000";
this.el.addEventListener( "mousedown", this.onMouseDown.bind(this) );
}
Canvas.prototype.onMouseDown = function() {
console.log( 'onMouseDown: ', this.el );
}
no var
you make _self a globle val