JS TOOLS
Angular 1.5.x & lodash 4.x
QUESTION
I’m trying to create an object factory pattern that creates object / classes . In my example below I’m create object models for content types e.g. Article, Document, Images, etc. Given my skill limitations I’m replicating the Article example below for every content type. Is there a way in JavaScript to create a dynamic object class with a unique prototype.
CURRENT APPROACH
// constructor injection
_Constructor.$inject = [];
function _Constructor() {
function __constructor(data, keys) {
_.assign(this, _.pick(data, keys));
}
return __constructor;
}
// one of many content type models
Article.$inject = ['__constructor'];
function Article(__constructor) {
function Article(data) {
var fillables = Object.freeze(['id','title','subtitle','body','body']);
__constructor.call(this, data, fillables);
}
Article.prototype = Object.create(__constructor.prototype);
Article.prototype.constructor = Article;
return Article;
}
IDEAL OUTCOME
Create a content type model factory pattern that allows me to create unique content type object models. Pseudo example:
var documentFillables = Object.freeze(['id', 'name', 'body']),
documentData = {id:1,name:'My Document', body: 'coolbody stuff'},
Document = new ModelFactory('Document', documentData, documentFillables),
articleFillables = Object.freeze(['id', 'title', 'subtitle']),
articleData = {id:1,title:'My Article', subtitle: 'My Subtitle'},
Article = new ModelFactory('Article', articleData, articleFillables);
Note I've played around with merge, extend and clone and although I can replicate and extend objects I end up with a fair amount of code redundancy and/or generic objects i.e. have many ModelFactory() but no Article().