【问题标题】:OO Javascript: array not getting initializedOO Javascript:数组未初始化
【发布时间】:2018-10-17 02:47:15
【问题描述】:

我正在编写一个包含三个类的库(使用 ES6 Javascript):开放时间、书籍、书籍。以及“主”类库(由以前的类组成)。

我得到的控制台错误如下:Uncaught TypeError: Cannot set property 'undefined' of undefined at Books.set books [as books]。

错误出现在 setter 的 Books 类中。

代码如下:

'use strict';
//OO library (Classes: Libary, Book, WorkingHours)
class WorkingHours{
    constructor(open, close, lunch){
        this.open = open;
        this.close = close;
        this.lunch = lunch;
    }
}
class Book {
    constructor(title, category, author){
        this.title = title;
        this.category = category;
        this.author = author;
    }
}
class Books {
    constructor(){
        this.books = [];
        //let books = new Array();
        //let books = [];
        var bookAmount = 0;
    }
    set books(book){
        //this.books.push(book);
        this.books[this.bookAmount] = book;
        this.bookAmount++;
    }
}
class Library { 
    constructor(workingHours, booksIn){
        this.workingHours = workingHours;
        this.booksIn = booksIn;
    }

    get workingHours() {
        return this.workingHours;
    }
    get booksIn() {
        return this.booksIn;
    }
}

var workHour = new WorkingHours(900,1700,false);
var bookColl = new Books();
var newBook = new Book("Mastery", "Real Stories", "Robert Greene");
bookColl.books = newBook;
newBook = new Book("48 Laws of Power", "Slef-teaching", "Robert Greene");
bookColl.books = newBook;
var newLib = new Library(workHour, bookColl);
console.log(newLib);

【问题讨论】:

  • 您不能拥有两个同名的属性。 .books 不能既是(setter)方法又是数组,.workingHours.booksIn 如果只有 getter 并且是无限递归的,则不能设置
  • estus 答案是正确的。请注意,您在那里有两个不同的问题。试试这个教程,它非常清楚地解释了 Javascript OOP。 youtube.com/watch?v=PFmuCDHHpwk&t=3252s
  • 感谢您的教程和帮助。它现在可以工作了!

标签: javascript arrays oop ecmascript-6 initializer


【解决方案1】:

var bookAmount = 0 不初始化属性。 this.books = [] 导致 books 数组通过 books setter 分配,就像在类外分配一样,this.books[this.bookAmount] = ...booksbookAmount 未定义的情况下进行评估。

应该是:

class Books {
    constructor(){
        this._books = [];
        this.bookAmount = 0;
    }
    ...
}

bookAmount 值是多余的,因为它已经作为this._books.length 可用。正确的做法是:

set books(book){
    this._books.push(book);
}

get books(){
    return this._books;
}

【讨论】:

  • 非常感谢,它现在按我的预期工作了 :)
猜你喜欢
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多