Skip to content Skip to sidebar Skip to footer

Inheriting A Class That Has The Same Constructor But Different/similar Prototypes

Suppose I have a constructor: function Constructor(input) { this.input = input } Constructor.prototype.method = function() { console.log('a') } But I want to make another cla

Solution 1:

var inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /** @override */
  childCtor.prototype.constructor = childCtor;
};



// How to use it:

var Constructor1 = function() {
//add all your methods, variables etc
};

Constructor1.prototype.myMethod = function() {
};

var Contructor2 = function() {
Contructor1.call(this); // Call the super class constructor
};
inherits(Contstructor2, Constructor1);
// Constructor2 now inherits from Constructor1
// override, add methods variables etc, whatever you need.

// Have fun!

Solution 2:

Okay, much easier just to use apply:

function newConstructor(Super) {
  function Construct() {
    Super.apply(this, arguments)
  }

  require('util').inherits(Construct, Super)

  return Construct
}

Solution 3:

Here's a nasty-ish solution:

function Constructor1(input) {
  this.input = input;
}

Constructor1.prototype.method = function() {
  console.log('a');
}

// be careful here: evals the string value of Constructor1 with references to "Constructor1" changed to "Constructor2"
eval(Constructor1.toString().replace("Constructor1", "Constructor2"));

Constructor2.prototype.method = function() {
  console.log('b');
}

var c1 = new Constructor1(1);
var c2 = new Constructor2(2);
console.log(c1.constructor === c2.constructor) // true

c1.method() // a
c2.method() // b

Post a Comment for "Inheriting A Class That Has The Same Constructor But Different/similar Prototypes"