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?

3
  • How does util.inherits look like? You can save a reference to the parent constructor there if you need it. Commented Jan 30, 2014 at 1:56
  • I think util.inherits is from Node.js. Commented Jan 30, 2014 at 2: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). Commented Jan 30, 2014 at 2:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.