[英]Javascript - Cannot instantiate multiple instances of the same object
我試圖實例化同一對象的多個實例。 第一個實例化工作正常,但是當我嘗試初始化另一個對象時,我收到此錯誤,
Uncaught TypeError: Object #<draw> has no method 'width'
這是小提琴 ,這是我的代碼:
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);
總之,我的目標是實例化同一“類”的多個實例。
您正在重新定義halo
cunstructor:
var halo = new halo(); // <-- change variable name to halo1
halo.width(500);
var halo2 = new halo();
halo2.width(300);
修正版: http : //jsfiddle.net/GB4JM/1/
我會建議一些結構更像這樣的東西:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.