0

Say I got this JS code

function Parent(){}
Parent.prototype.do = function(){ // Get here the Child(1|2)'s class name }

function Child1(){}
Child.prototype = new Parent();

function Child2(){}
Grandson.prototype = new Parent();

Child1.do();
Child2.do();

I know that there was a (currently deprecated) "caller" info within arguments.

How can this be done? Is this a common pattern of doing things in JavaScript, or is it an anti-pattern? How is usually done this type of stuff?

Michael
  • 4,786
  • 11
  • 45
  • 68
  • 1
    It would be better to use Object.create to set prototype of Child instead of creating an instance of Parent. http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Oct 30 '14 at 23:35

1 Answers1

0

You can reset your constructor property of the child prototype objects and access this property in the do function:

function Parent(){}
Parent.prototype.do = function(){ 
    var name = this.constructor.toString().match(/function ([^(]+)/)[1];
    console.log(name);
}

function Child1(){}
Child1.prototype = new Parent();
Child1.prototype.constructor = Child1;

function Child2(){}
Child2.prototype = new Parent();
Child2.prototype.constructor = Child2;

new Child1().do(); // logs Child1
new Child2().do(); // logs Child2

DEMO

An alternative is to add an additional property to the prototype of the child object, e.g. className:

function Parent(){}
Parent.prototype.do = function(){ 
    var name = this.className;
    console.log(name);
}
Parent.prototype.className = 'Parent';

function Child1(){}
Child1.prototype = new Parent();
Child1.prototype.className = 'Child1';

function Child2(){}
Child2.prototype = new Parent();
Child2.prototype.className = 'Child2';

new Child1().do(); // logs Child1
new Child2().do(); // logs Child2
friedi
  • 4,350
  • 1
  • 13
  • 19