我正在创建有很多属性的对象,我想知道最佳实践是什么。看起来构造函数过长会很糟糕(实例化新对象不好玩)。
function Book(title, author, pages, chapters, publisher, datePublished, authorHometown, protagonistFavoriteColor) {
this.title = title;
this.authorpages = authorpages;
this.pages = pages;
this.chapters = chapters;
this.publisher = publisher;
this.datePublished = datePublished;
this.authorHometown = authorHometown;
this.protagonistFavoriteColor = protagonistFavoriteColor;
}
// not reliable to remember how to order params
var rc = new Book("Robinson Crusoe", "Daniel Defoe", 342, 16, ...);
我在想,也许我应该在构造函数中设置三个重要属性(例如标题、作者和页面),并为其余的属性编写单独的setter方法以保持一致性?如果采用这种设置方式是最好的路径,那么在JS中是否有很好的方式来强制调用这些方法(有点像Java中的接口)?
function Book (title, author, pages){
this.title = title;
this.author = author;
this.pages = pages;
this.chapters = null;
this.publisher = null;
this.datePublished = null;
this.authorHometown = null;
this.protagonistFavoriteColor = null;
}
var rc = new Book("Robinson Crusoe", "Daniel Defoe", 342);
rc.setChapters(16);
rc.setPublisher("John Smith Co.");
rc.setDatePublished("04-25-1719");
rc.setAuthorHometown("London");
rc.setProtagonistFavoriteColor("lilac");
// we'd also want to mandate that these setters be called so nothing is left null