I have an object that looks something like this:
var myObj = {
_fooCon: function(f) {
if (typeof f != 'function') throw new TypeError('Bad Foo');
this.fn = f;
},
_barCon: function(f) {
if (typeof f != 'function') throw new TypeError('Bad Bar');
this.fn = f;
},
someFoo: function(v) {
return new this._fooCon(function(x) {
return x + ' Foo ' + v;
});
},
someBar: function(v) {
return new this._barCon(function(x) {
return x + ' Bar ' + v;
});
}
};
The reason for doing this is so I can use instanceof productively (i.e., so I can distinguish between the two objects, which are used in different scenarios, despite being structurally identical). (Ignore the fact that someFoo and someBar are similar!)
Is there a way I can abstract the constructor functions, so if I need to create, say, _bazCon, I don’t need to repeat myself; or, if there’s a bug, I don’t have to fix every constructor definition?
I tried making a factory member, like this:
_factory: function(type, f) {
if (typeof f != 'function') throw new TypeError('Bad ' + type);
this.fn = f;
}
…then:
_fooCon: function(f) { return new this._factory('Foo', f); }
Even without trying this, I can see it’s not going to work! Any ideas on how to achieve what I’m looking for?
If your functions really do the same thing, then it’s as simple as this:
If there’s other behavior that differentiates them, then you could have
_factoryreceive a function argument that is invoked within the constructor. That function could use.callor.applyto set thethisvalue to the object being constructed.A different approach would be to use a constructor to create
myObj, and take advantage of the variable scope so that you don’t need to expose the_xxxConconstructors.This uses an anonymous function as a constructor, since we don’t need it again.
You don’t necessarily need the outer function to be used as a constructor, but you do need a function that returns an object to
myObj.If you did want to expose the
_xxxConfunctions, then changevartothis., and put thethis.back insomeFooandsomeBar.