假设我们有一本书的3章,它们位于自己的URL上,如下所示:
第1章= /1.html
第2章= /2.html
第3章= /3.html
现在假设我们要考虑面向对象,并创建2个JS对象(借助jQuery):
章节:将章节加载到元素中,以及
书籍:垂直显示章节(一个接一个)。
JS代码:
// Chapter
function Chapter(chapterId)
{
this.chapterId = chapterId;
}
Chapter.prototype =
{
getChapterId: function()
{
var chapterId = this.chapterId;
return chapterId;
},
loadChapter: function(el)
{
$(el).load( this.getChapterId + ".html" ); // Ajax
}
}
// Book
function Book()
{
// ?
}
Book.prototype =
{
// ?
}
您认为以面向对象的方式定义对象“ Book”以及原型中的方法的最佳方法是什么?
在Book.prototype中处理对象“章”实例化的最优雅方法是什么?
谢谢
最佳答案
我只是将章节ID作为参数传递给Book
并将章节加载到数组中。像这样:
// Book
function Book(chapters) {
this.chapters = chapters.map(function(id){ return new Chapter(id) });
}
var book = new Book([1,2,3,4]);
然后,您可以创建方法来循环章节并根据需要进行操作。