2

Say you have an object hierarchy in javascript where "A" is the superclass and both "B" and "C" inherit from it. You have some methods in "A" that want to create and return a new instance of whatever type of object it actually is. Thus, if one of these methods in object "A" is called on an object that is of type "B", it should create a new object of type "B" and return it, but obviously object "A" doesn't know anything about "B" (and shouldn't).

So, how do you create an object of the same type of some other object regardless of what type it is (as illustrated in the invert method)?

Code example:

function A() {
    // constructor logic here
}

A.prototype = {
    invert: function() {
        // question: how do I create an object here that is the same
        // type as whatever this object is (could be A, B or C)
    }
};

// -------------------------

// B - subclass of A
function B() {
    // call A superclass constructor
    A.apply(this, arguments);
}

B.prototype = new A();
B.prototype.constructor = B;

// methods of B
B.prototype.negate = function() {
        // method of subclass
}

// -------------------------

// C - subclass of A
function C() {
    // call A superclass constructor
    A.apply(this, arguments);
}

C.prototype = new A();
C.prototype.constructor = C;
jfriend00
  • 683,504
  • 96
  • 985
  • 979

1 Answers1

1

If you carefully restore constructors (like you already do in your example) you can just call 'new this.constructor()':

function A () {
  this.label = 'A';
}

A.prototype = {
  constructor: A,
  quux: function () {
    return new this.constructor(/*ctor args here*/);
  }
};

function B () {
  this.label = 'B';
}

B.prototype = new A();
B.prototype.constructor = B;

function C () {
  this.label = 'C';
}

C.prototype = new A();
C.prototype.constructor = C;

console.log(new A().quux().label); // prints A
console.log(new B().quux().label); // prints B
console.log(new C().quux().label); // prints C
Community
  • 1
  • 1
aemxdp
  • 1,348
  • 1
  • 14
  • 34