我正在创建具有很多属性的对象,我很好奇实例化它们的最佳实践。看起来真的有很长的构造函数是很糟糕的(实例化新对象并不好玩)。JavaScript中长构造函数的最佳实践
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, ...);
如果也许我应该只是在构造函数(e.g.title,作者和页)设置也许三个重要特性,写的其他个人制定者我不知道。或者为了一致性,我应该只使用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
最后,将传递一个对象到我的构造函数和解构它完败构造的PT?
在施工的时候,你有(或必须)所有的值之前创建对象的实例? - 我知道在某些情况下,您希望使用您手边的信息获取实例,然后从数据源或用户输入中获取其余部分(如果需要)。如果是这种情况,我会推荐builder模式 - 以这个小提琴为例:https://jsfiddle.net/brandonscript/p516ojn0/ – ochi