admin管理员组文章数量:1278851
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".
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".
Share Improve this question asked Mar 22, 2013 at 5:37 JohnJohn 2651 gold badge3 silver badges8 bronze badges2 Answers
Reset to default 8You 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/GB4JM/1/
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();
本文标签: oopJavascriptCannot instantiate multiple instances of the same objectStack Overflow
版权声明:本文标题:oop - Javascript - Cannot instantiate multiple instances of the same object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741212166a2359339.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论