[英]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.