admin管理员组文章数量:1420145
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
本文标签: objectJavaScript multiple instancesStack Overflow
版权声明:本文标题:object - JavaScript multiple instances - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745326241a2653604.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论