factory-helper
v1.0.0
Published
A function prototype for easier constructors
Downloads
2
Readme
factory
This is a silly experiment, mostly.
Silly or not, the idea behind this is the opinion that this common js trick is not DRY, and is probably anti-pattern:
function Thing(attr) {
if (!(this instanceof Thing)) {
return new Thing(attr);
}
...
}
It'd be better if we had an idiom that didn't necessitate repeating the name of the constructor three times.
This aims to solve the problem, but with the caveat that you cannot call the constructor recursively. Yet the only reason I usually see for calling a constructor recursively is to implement the above—the pain point that this module aims to eliminate in the first place. :)
However, I don't know if it's rubbish, and I've never used it at scale on a real project.
usage
require('./factory.js').expose()
var Robot = function (calibration) {
this.calibration = calibration;
}.factory();
Robot.prototype.signal = function signal() {
return this.calibration.signal;
};
Robot.prototype.attack = function attack(opponent) {
console.log(this.signal(), ' > ', opponent.signal());
};
var bob = Robot({ signal: 'beep' });
var bill = Robot({ signal: 'boop' });
bob.attack(bill);
bill.attack(bob);