TL;DR:
Do we need factories/constructors in prototypical OO? Can we make a paradigm switch and drop them completely?
The BackStory:
I've been toying with doing prototypical OO in JavaScript lately and find that 99% of OO done in JavaScript is forcing classical OO patterns into it.
My take on prototypical OO is that it involves two things. A static prototype of methods (and static data) and a data binding. We don't need factories or constructors.
In JavaScript these are Object literals containing functions and Object.create
.
This would mean we can model everything as a static blueprint/prototype and a data binding abstraction that's preferably hooked straight into a document-style database. I.e. objects are taken out of the database and created by cloning a prototype with the data. This would mean there is no constructor logic, no factories, no new
.
The Example code:
An pseudo example would be :
var Entity = Object.create(EventEmitter, {
addComponent: {
value: function _addComponent(component) {
if (this[component.type] !== undefined) {
this.removeComponent(this[component.type]);
}
_.each(_.functions(component), (function _bind(f) {
component[f] = component[f].bind(this);
}).bind(this));
component.bindEvents();
Object.defineProperty(this, component.type, {
value: component,
configurable: true
});
this.emit("component:add", this, component);
}
},
removeComponent: {
value: function _removeComponent(component) {
component = component.type || component;
delete this[component];
this.emit("component:remove", this, component);
}
}
}
var entity = Object.create(Entity, toProperties(jsonStore.get(id)))
The minor explanation:
The particular code is verbose because ES5 is verbose. Entity
above is a blueprint/prototype. Any actual object with data would be created by using Object.create(Entity, {...})
.
The actual data (in this case the components) is directly loaded from a JSON store and injected directly into the Object.create
call. Of course a similar pattern is applied to creating components and only properties that pass Object.hasOwnProperty
are stored in the database.
When an entity is created for the first time it's created with an empty {}
The actual Questions:
Now my actual questions are
- Open source examples of JS prototypical OO?
- Is this a good idea?
- Is it in-line with the ideas and concepts behind prototypical OOP?
- Will not using any constructors/factory functions bite me in the ass somewhere? Can we really get away with not using constructors. Are there any limitations using the above methodology where we would need factories to overcome them.