我正在創建具有很多屬性的對象,我很好奇實例化它們的最佳實踐。看起來真的有很長的構造函數是很糟糕的(實例化新對象並不好玩)。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