Reputation: 2001
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();
})();
Upvotes: 0
Views: 4223
Reputation: 96800
When not using var
on 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 el
an object property:
var Canvas = function(el) {
this.el = el;
};
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);
});
};
Upvotes: 4
Reputation: 845
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
Upvotes: 2