简体   繁体   中英

Javascript - How to call a method in another method within the same class

How can I call a method in another method within the same class in javascript. I have tried calling it

this.save(books);

like so. but I get an error:

Uncaught TypeError: this.save is not a function

Any Suggestions

class Book {
  constructor(title, author, isbn) {
    this.title = title;
    this.author = author;
    this.isbn = isbn;
  }

  static getBooks() {
    const books = localStorage.getItem('books');
    return books === null ? [] : JSON.parse(books);
  }

  static displayBooks() {
    const books = Book.getBooks();
    books.forEach((book) => {
      const ui = new UI();
      ui.addBookToList(book);
    });
  }

  static addBook(book) {
    console.log(this);
    const books = Book.getBooks();
    books.push(book);
    this.save(books);
  }

  static removeBook(isbn) {
    const books = Book.getBooks(),
      bookIndex = books.findIndex((book) => book.isbn === isbn);
    books.splice(bookIndex, 1);
    this.save(books);
  }

  save(books) {
    localStorage.setItem('books', JSON.stringify(books));
  }
}

Static methods are called on class itself and not an instance of the class either make save method static or make caller method non static.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM