Reputation: 265
I am trying to instantiate multiple instances of the same object. The first instantiation works fine, but when I try to initialize another object, I get this error,
Uncaught TypeError: Object #<draw> has no method 'width'
here is the fiddle, and here is my code:
function halo() {
var width = 720, // default width
height = 80; // default height
function draw() {
// main code
console.log("MAIN");
}
draw.width = function(value) {
if (!arguments.length) return width;
width = value;
return draw;
};
draw.height = function(value) {
if (!arguments.length) return height;
height = value;
return draw;
};
return draw;
}
var halo = new halo();
halo.width(500);
var halo2 = new halo();
halo2.width(300);
In summary, my objective is to instantiate multiple instances of the same "class".
Upvotes: 2
Views: 6761
Reputation:
I would suggest something structured a little more like this:
Halo = (function() {
function Halo(width, height) {
this.width = width || 720; // Default width
this.height = height || 80; // Default height
}
Halo.prototype = {
draw: function() {
// Do something with this.width and this.height
}
};
return Halo;
})();
var halo = new Halo(500, 100);
halo.draw();
var halo2 = new Halo(300, 100);
halo2.draw();
Upvotes: 4
Reputation: 193281
You are redefining halo
cunstructor:
var halo = new halo(); // <-- change variable name to halo1
halo.width(500);
var halo2 = new halo();
halo2.width(300);
Fixed version: http://jsfiddle.net/GB4JM/1/
Upvotes: 8