Çok sayıda özelliği olan nesneler oluşturuyorum ve bunları oluşturmak için en iyi uygulamaları merak ediyorum. Gerçekten çok uzun kurucuların olması oldukça kötü gibi görünüyor (yeni nesnelerin başlatılması eğlenceli değil). belki de sadece yapıcı (e.g.title, yazar ve sayfa) içinde belki üç önemli özellikleri ayarlamak ve geri kalanı için bireysel ayarlayıcılar yazmalıyım eğer JavaScript'te Uzun Ekstrüktörler İçin En İyi Uygulamalar
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, ...);
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
Son olarak, benim yapıcı bir nesne geçirerek ve bir yapıcısının nk toplam yenilgi kurucuların ki?
, sen var mı (ya da olması gerekir) önce tüm değerleri nesnenin örneğini oluşturmak? - Bazı durumlarda örneği elinizde tuttuğunuz bilgilerle almak ve geri kalanını (gerekirse) veri kaynağı veya kullanıcı girdisinden almak istediğinizi biliyorum. Bu durumda, yapımcı modelini öneriyorum - bir örnek olarak şu bilmeceye bakın: https://jsfiddle.net/brandonscript/p516ojn0/ – ochi