0

If I have the following:

function Constructor1(data){
...
...
...};


function Constructor2(data){
Constructor1.prototype.constructor.call(this, data);
...
...
...
}

Constructor2.prototype = new Constructor1();

Then how can I later determine the difference between how they were constructed? I know I can do if (testObject instanceof Constructor2) but if I have a LOT of inherited objects I don't want to do that test for everything. Is there any way to get the string 'Constructor2' returned somehow? (Or whatever the first constructor function called) is?

asolberg
  • 6,638
  • 9
  • 33
  • 46
  • What do you mean "you don't want to test for everything"? At any given place you do want to test for *one* thing only. – Bergi Apr 11 '14 at 01:23

1 Answers1

1
  1. You can call the parent like this: Parent.call(this,args).
  2. You should not create an instance of Parent to set the prototype part of the inheritance in Child.

If you set the prototype without destroying the prototype.constructor in Child you can use the name property of the constructor function:

function Parent(args){
};
function Child(args){
  Parent.call(this,args);
};
console.log(Child.prototype.constructor.name);//=Child
//overwrithing Child.prototype so also Child.prototype.constructor
Child.prototype=Object.create(Parent.prototype);
console.log(Child.prototype.constructor.name);//=Parent, needs to be fixed
Child.prototype.constructor=Child;//fixed
var c = new Child();
console.log(c.constructor.name);//=Child

The name property of Function isn't standard so no guarantee about it's behavior:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

You may want to check using the function itself: (this.constructor===Parent)

More on constructor functions and prototype here.

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160