简体   繁体   English

Javascript - 如何在同一个类中的另一个方法中调用一个方法

[英]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.如何在javascript中的同一类中的另一个方法中调用方法。 I have tried calling it我试过调用它

this.save(books);

like so.像这样。 but I get an error:但我收到一个错误:

Uncaught TypeError: this.save is not a function未捕获的类型错误:this.save 不是函数

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.静态方法是在类本身上调用的,而不是类的实例,要么使save方法为静态,要么使caller方法为非静态。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从JavaScript中的同一对象中的另一个方法调用方法? - How to call a method from another method within the same object in JavaScript? 如何在Javascript的同一类中调用另一个方法 - How do I call another method from within the same class in Javascript 在javascript中,如何从同一个类中的另一个方法调用类方法? - In javascript, how do I call a class method from another method in the same class? 如何从另一个方法中正确调用类方法 - How to properly call a class method from within another method Javascript原型:如何在另一个方法中调用一个方法? - Javascript prototype: how do I call a method within another method? 如何在Javascript类中的另一个方法内调用一个方法? - How to call a method inside another method in a class in Javascript? 在Java语言中此上下文不同的情况下,调用相同“类”的另一个方法吗? - Call another method of the same “class” with this context being different in Javascript? 从另一个方法调用javascript类方法 - Call javascript class method from another method Javascript 自定义类方法在使用 Babel 后不能调用同一个类中的另一个方法 - Javascript custom class method cannot call another method in same class after using Babel 从JavaScript中的另一个类调用一个类方法? - Call a class method from a another class in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM