3

I have a class that inherits from another. Within the base class, I'm wondering if it is possible to create and return a new instance of the calling parent class.

Here's an example:

Base:

var util = require('util');

var ThingBase = function(options) {
}

ThingBase.prototype.mapper = function(data) {
  // do a bunch of stuff with data and then
  // return new instance of parent class
};

Parent:

var FooThing = function(options) {
  ThingBase.call(this, options);
};

util.inherits(FooThing, ThingBase);

FooThing.someMethod = function() {
  var data = 'some data';
  var newFooThing = this.mapper(data); // should return new FooThing instance
};

The reason why I wouldn't just create a new instance from someMethod is that I want mapper to do a bunch of stuff to the data before it returns an instance. The stuff it will need to do is the same for all classes that inherit from Base. I don't want to clutter up my classes with boilerplate to create a new instance of itself.

Is this possible? How might I go about achieving something like this?

doremi
  • 14,921
  • 30
  • 93
  • 148
  • How does `util.inherits` look like? You can save a reference to the parent constructor there if you need it. – elclanrs Jan 30 '14 at 01:56
  • I think `util.inherits` is from Node.js. – Whymarrh Jan 30 '14 at 02:10
  • 2
    I fear you confuse the terminology? Usually a `Child` class does inherit from a `Parent` class, or a `Specific` class does inherit from a `Base` class. I've never heard of a `Parent` inheriting from anything (unless you have 3 classes in the discussed hierarchy, then there might be a `GrandParent`). – Bergi Jan 30 '14 at 02:11

1 Answers1

3

Assuming that FooThing.prototype.constructor == FooThing, you could use

ThingBase.prototype.mapper = function(data) {
  return new this.constructor(crunch(data));
};

All other solutions would "clutter up [your] classes with boilerplate [code]", yes, however they don't rely on a correctly set constructor property.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This is exactly what I needed. I didn't know about the constructor prototype. Thanks for that. In my case, I do have a correctly set constructor property via util.inherits, so this works perfectly. – doremi Jan 30 '14 at 16:41