【发布时间】:2023-03-05 22:53:01
【问题描述】:
假设我们有一本书的 3 个章节,并且它们位于各自的 URL 上,如下所示:
- 第 1 章 = /1.html
- 第 2 章 = /2.html
- 第 3 章 = /3.html
现在假设我们想考虑 OO 并创建 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 中处理对象“Chapter”实例化的最优雅的方式是什么?
谢谢
【问题讨论】:
标签: javascript jquery oop design-patterns prototype