Object.prototype中的对象实例化

OO Javascript - Objects instantiation in Object.prototype

本文关键字:对象 实例化 prototype Object      更新时间:2023-09-26

假设我们有一本书的三个章节,它们位于自己的URL上,像这样:

  • 第一章=/1.html
  • 第二章=/2.html
  • 第三章=/3.html

现在假设我们想要考虑OO并创建两个JS对象(在jQuery的帮助下):

  • Chapter:将章节加载到元素中,
  • Book:垂直显示章节(一个接一个)

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"实例化的最优雅的方法是什么?

谢谢

我将把章节id作为Book的参数传递,并将章节加载到数组中。像这样:

// Book
function Book(chapters) {
  this.chapters = chapters.map(function(id){ return new Chapter(id) });
}
var book = new Book([1,2,3,4]);

然后您可以创建方法来循环章节并根据需要操作它们。

啊,我之前没看清楚你的问题。我会这样做:

// Chapter
var Chapter = function(chapterId) {
    this.chapterId = chapterId;
}
Chapter.prototype.loadChapter: function(el) {
    $(el).load( this.chapterId + ".html" ); // Ajax
}

// Book
var Book = function(chapters) {
    this.chapters = (chapters) ? chapters : [];
    this.numberOfChapters = (chapters) ? chapters : 0; 
    // assume that this has to make sence, so if it is number of chapters, 
    // it start with 0.
}
Book.prototype.addChapter = function () {
    this.chapters.push(new Chapter(++this.numberOfChapters));
}

你试过了吗:

(function (namespace, chapterId) {
    var Chapter = function (chapterId) {
        this.chapterId = chapterId;
    }
    Chapter.prototype ={
    getChapterId: function () {
        var chapterId = this.chapterId;
        return chapterId;
    },
    loadChapter: function (el) {
        $(el).load(this.getChapterId + ".html"); // Ajax
    }}
    namespace.Chapter = Chapter;
})(new Book(), chapterId);