Reputation: 1111
I want to create a "library" with multiple "shelves", but I can't figure out how to name each shelf differently while creating them using a for loop:
function library(initLibraryName, initNumberOfShelves, initNumberOfBooks)
{
this.name = initLibraryName;
this.numberOfShelves = initNumberOfShelves;
this.numberOfBooks = initNumberOfBooks;
for (var i = 0; i < numberOfShelves; i++)
{
this.shelf = new shelf(i, numberOfBooks/numberOfShelves);
}
}
Upvotes: 2
Views: 3527
Reputation: 1111
Thanks to: https://stackoverflow.com/users/3052866/user3052866
I realize now that I needed to have an array of shelves in my library class, and that you can't just create multiple objects as part of a function in JS!
Thanks to elclanrs for pointing out the latter!
Upvotes: 1
Reputation: 46
I'm not sure why you creating new instances of shelf, but at first you should declare it
// by convention constructor name should start with uppercase letter
function Library(initLibraryName, initNumberOfShelves, initNumberOfBooks) {
this.name = initLibraryName;
this.numberOfShelves = initNumberOfShelves;
this.numberOfBooks = initNumberOfBooks;
this.shelf = []; // at first you need to define an array
for (var i = 0; i < numberOfShelves; i++) {
// then push Shelf instances to an array
this.shelf.push(new Shelf(i, this.numberOfBooks / this.numberOfShelves));
}
}
function Shelf(arg1, arg2) {
this.prop1 = arg1;
this.prop2 = arg2;
this.method = function () {
// some logic
}
}
Upvotes: 2