first, this is my code:
var rettangolo = {
rectX_top: 0,
recX_bottom: 0,
rectY_top: 0,
rectY_top: 0,
colpito: false,
colore: 'hsl(' + 360 * Math.random() + ', 50%, 50%)',
rettangolo: function() {
this.setRectX_top(0);
this.setRectX_bottom(0);
this.setRectY_top(0);
this.setRectY_top(0);
this.setColpito(false);
this.setColore('red');
},
setColpito: function(colpito) {
this.colpito = colpito;
},
setColore: function(colore) {
this.colore = colore;
},
setRectY_top: function(top) {
rectY_top = top;
},
setRectX_top: function(top) {
rectX_top = top;
},
setRectX_bottom: function(bottom) {
rectX_bottom = bottom;
},
setRectY_bottom: function(bottom) {
rectY_bottom = bottom;
},
<!-- GET METHODS -->
getColore: function() {
return this.colore;
},
getRectY_top: function() {
return this.rectY_top;
},
getColpito: function() {
return this.colpito;
},
getRectX_top: function() {
return this.rectX_top;
},
getRectX_bottom: function() {
return this.rectX_bottom;
},
getRectY_bottom: function() {
return this.rectY_bottom;
},
}
This is my class, and now I need to create multiple instances of this class. Is it possible? And if it is, how do you achieve it? (Plus, is it correct? notice that this is the first class I create as they never explained it at school). Thank you!
-
no, it's not correct. Look for "javascript constructors".Alnitak– Alnitak2015年12月02日 22:24:40 +00:00Commented Dec 2, 2015 at 22:24
-
You wrote object and not a class. If you need multiple instances, write function.Maxim Goncharuk– Maxim Goncharuk2015年12月02日 22:29:39 +00:00Commented Dec 2, 2015 at 22:29
1 Answer 1
You need to make a constructor or a factory function.
Read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Constructor function vs Factory functions
There are many ways to achieve this this is one of them. Obviously you can extend it to fit your case.
var object = function(options) {
var object = {
id: options.id,
property: 'value'
};
return object;
};
var a = object({id:1});
var b = object({id:2});
console.log(a);
console.log(b);
This illustrates that you can create two objects from the same constructor obvious by that both objects have the same value in the property attribute and a different id dependant on the id option passed.
Additionally the line comment:
<!-- GET METHODS -->
Will throw an error, in Javascript use either // or /* */ for comments.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar