For instace – I need to create a class that can be used to create multiple farms. Each farm must contain an id, a location and an array of animals. Each animal must have a name and quantity (so basically an animal will be an object).
I don’t know how to put this array of animals inside the class.
class Farms {
constructor (id, location, animals) {
this.id = id;
this.location = location;
this.animals = animals;
} – how can I make ‘animals’ into an array?
4
Answers
If you want to go OOP way then it’s better to create an Animal class as well and pass an array of that.
If you don’t want to create Animal class. You can just pass array of objects that defines animal.
Create
Animal
class, instantiate some animals from that class, and pass it toFarm
object:Note: It’s generally a good practice to use singular nouns instead of plural nouns for naming classes.
e.g. name your class
Farm
instead ofFarms
.For the record: without the
class sugar
and as OOP as anything:Small refactoring to @XMehdi01 answer. Keep constructor arguments followed by an underscore to keep the readability and clarity for future.