say I have a class BaseClass and two classes ClassA and ClassB which inherit from BaseClass via
ClassA.prototype = Object.create( BaseClass.prototype );
I want to write a method that, if called from an instance of ClassA, returns a new instance of ClassA and if called from an instance of ClassB, returns a new instance of ClassB – and I'm wondering what the best way is to do so.
Currently, after fiddling around, I came up with the following solution, which seems to work just fine:
// this is added additionally to the above mentioned inheritance setup
ClassA.prototype.constructor = ClassA;
ClassB.prototype.constructor = ClassB;
BaseClass.prototype.newInstance = function () {
var constructor = this.constructor,
ClassFactory = constructor.bind.apply( constructor, [constructor].concat( [].slice.call( arguments ) ) );
return new ClassFactory();
};
The obvious downside is to overwrite the prototype's constructor, which feels wrong, because the prototype's constructor in fact was BaseClass.
Another way that should work is the approach of overriding:
BaseClass.prototype.newInstance = function () {
throw new Error( 'Cannot call abstract method.' );
};
/** @override */
ClassA.prototype.newInstance = function () {
var ClassFactory = ClassA.bind.apply( ClassA, [ClassA].concat( [].slice.call( arguments ) ) );
return new ClassFactory();
};
// ... do the same for ClassB
Now my question would be asking for some insight on which strategy is better and why, what are up- and downsides to each and maybe even if there is a better way?
Edit: To clarify what the goal is, I want to end up doing something like this:
BaseClass.prototype.someMethod = function () {
var instance = this.getInstance();
instance.someMethod();
return instance;
};
Now, since ClassA and ClassB will inherit this method, I want it to return a new instance of the same class that it was called from.