我怎样才能让这段Javascript代码更加干燥?
这是奥丁项目的一项作业。当我进行测试时,我意识到这段代码很糟糕,因为它不是 DRY。我只会创造越来越多的书籍对象。我怎样才能让这个更干净?
let myLibrary = [];
function Book(title, author, pages, hasRead){
this.title = title;
this.author = author;
this.page = pages;
this.hasRead = hasRead;
};
function addBookToLibrary(newBook){
return myLibrary.push(newBook)
};
let newBook = new Book("Wool", "Hugh Howey", "592", false);
let lifeOfPi = new Book("Life of Pi", "Yann Martel", "392", false);
addBookToLibrary(newBook);
addBookToLibrary(lifeOfPi);
console.log(myLibrary);
This is for one of the assignments on Odin Project. As i'm testing things out, i'm realizing how this code is bad because it's not DRY. I would just be creating more and more book objects. How can I make this more clean?
let myLibrary = [];
function Book(title, author, pages, hasRead){
this.title = title;
this.author = author;
this.page = pages;
this.hasRead = hasRead;
};
function addBookToLibrary(newBook){
return myLibrary.push(newBook)
};
let newBook = new Book("Wool", "Hugh Howey", "592", false);
let lifeOfPi = new Book("Life of Pi", "Yann Martel", "392", false);
addBookToLibrary(newBook);
addBookToLibrary(lifeOfPi);
console.log(myLibrary);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以做这样的事情,这样你就有了一个“BookLibrary”类。
You could do something like this, so that you have a "BookLibrary" class.