我想创建一个带有多个“架子”的“库”,但我无法弄清楚如何使用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);
}
}
答案 0 :(得分:1)
我不确定为什么要创建新的货架实例,但首先应该声明它
// 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
}
}
答案 1 :(得分:0)
感谢:https://stackoverflow.com/users/3052866/user3052866
我现在意识到我需要在我的库类中有一个架子数组,并且你不能只在JS中创建多个对象作为函数的一部分!
感谢elclanrs指出后者!