+ 5
I haven't understood the object and the object constructor lesson in JavaScript?Can anyone please help me ?
Can anyone explain it and send a book?
2 Respuestas
+ 4
Constructor's are like factories , you make the factory once and ask it to make any particular object as much you want .
So , for example -
function Car( ){
this.color = RED;
this.size = 20;
this.run = function (){
/* some code */
}
}
//and you can say later -
int audi = new Car();
int tesla = new Car()
tesla.run();
In this code the constructor car is the factory , color and size are attributes (information or data) of the car it will built and run is the function which will run the car .
So, when you say audi = new Car(); you make a new copy of the constructor Car named audi and you can get it's values and use its functions separately from other cars.
This topic is better understood in canvas examples .
+ 2
you can consider an object as a variable that has attributes an functionalities associated to it. E. G .A flower with leaves, petals, color (attributes) that grows and blooms (methods)
if you need only one flower you simply write the code for it: the variables and the methods associated to the flower object.
you can see that if you need 100 flowers you should write again everything for every single flower.
To avoid that you can write a constructor function that contains variables and methods for a flower.
You can instantiate and use as many flowers as you want from the same constructor function whithout having to write all the code for every single flower.