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