我正在尝试实例化同一对象的多个实例。第一个实例化工作正常,但是当我尝试初始化另一个对象时,我得到了这个错误,
Uncaught TypeError: Object #<draw> has no method 'width'
这是fiddle,这是我的代码:
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);
总之,我的目标是实例化同一“类”的多个实例。
答案 0 :(得分:8)
您正在重新定义halo
构造函数:
var halo = new halo(); // <-- change variable name to halo1
halo.width(500);
var halo2 = new halo();
halo2.width(300);
答案 1 :(得分:4)
我会建议更像这样的结构:
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();