我想创建一个具有多个“书架”的“库”,但我不知道如何在使用 for 循环创建它们时以不同的方式命名每个书架:
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);
}
}
最佳答案
我不知道为什么你要创建新的架子实例,但首先你应该声明它
// 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
}
}
关于javascript - 在循环中创建多个具有不同名称的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210161/