[英]Library.add is not a function error
我正在尝试执行以下代码:
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
Library.add(listItem);
console.log(Library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
HTML在这里:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
我想做的是按下addButton,onclick将在libraryUI对象下运行addBook函数。 然后,将在输入字段中使用书名,以创建带有书名的对象。 我想将该书添加到Library实例中的书列表(数组)中。 当我尝试使用以下代码执行此操作时,出现错误“未捕获的TypeError:Library.add不是函数”。 我以为Library.add 是一个函数。
我补充说:
var library = new Library();
因为我以为我忘记了创建Library的迭代,但是我仍然想出了完全相同的错误。 请帮忙。 :)
var addButton = document.querySelector("#add"); var searchButton = document.querySelector("#search"); var titleInput = document.querySelector("#title"); function Book(title) { this.title = title; } function Library() { this.books = []; } Library.prototype.add = function(book) { this.books.push(book); } var library = new Library(); //Library UI var libraryUI = { //Add a new book addBook: function() { var listItem = libraryUI.createNewBook(titleInput.value); library.add(listItem); console.log(library.books); }, //Create a new book createNewBook: function(title) { var book = new Book(title); return book; } }; addButton.addEventListener("click", libraryUI.addBook);
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Library App</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <h1>Personal Library</h1> <label for="title">Title: </label> <input type="text" id="title"> <button id="add">Add</button> <button id="search">Search</button> <p id="display"></p> <script src="js/app.js"></script> </body> </html>
它应该不是library.add
而不是Library.add
吗?
另外:为什么:
Library.prototype.add = function() { this.add = function(book) { this.books.push(book); }; }
代替:
Library.prototype.add = function(book) { this.books.push(book); }
?
如果我将Library.add
更改为library.add
和console.log(library.books)
我认为这console.log(library.books)
您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.