0

Can someone confirm if the bellow script is indeed the correct way for class inheritance within Javascript?

WRONG WAY

var Person = function () {
   this.className = this.constructor.toString().match(/^function ([a-z_0-9]+)\(/i)[1];
   console.log( this.className ); //ERROR
}

var Mark = function () {
   Person.call(this);
}

Mark.prototype             = Object.create( Person.prototype );
Mark.prototype.constructor = Mark;

new Person; // I LIKE TO DISPLAY 'Person'
new Mark; // I LIKE DISPLAY 'Mark'

CORRECT WAY

function Person () {
   this.className = this.constructor.toString().match(/^function ([a-z_0-9]+)\(/i)[1];
   console.log( this.className );
}

function Mark () {
   Person.call(this); // Class Mark extend Person
}

Mark.prototype             = Object.create( Person.prototype );
Mark.prototype.constructor = Mark;

function Matteo () {
    Mark.call(this); // Class Matteo extend Mark
}

Matteo.prototype             = Object.create( Mark.prototype );
Matteo.prototype.constructor = Matteo;

new Person; // Displays: 'Person'
new Mark; // Displays: 'Mark'
new Matteo; // Display: 'Matteo'
Mark
  • 16,906
  • 20
  • 84
  • 117
  • 1
    possible duplicate of [Javascript get Function Name?](http://stackoverflow.com/questions/2648293/javascript-get-function-name) – Hexaholic May 06 '15 at 09:31
  • Your code prints `undefined` – shyam May 06 '15 at 09:31
  • 1
    Which variable name are you looking to print? The name of the function itself? – David Hoelzer May 06 '15 at 09:33
  • Those names are variables, that are assigned after the function was parsed. They hold an anonymous function as their value – but this is not the same as a function name. See also: https://kangax.github.io/nfe/ – feeela May 06 '15 at 09:35

1 Answers1

3

This works for me:

function Person () {
  console.log(this.constructor.toString().match(/^function ([a-z_0-9]+)\(/i)[1]);
}

function Mark () {
  Person.call(this);
}

function Matteo() {
  Mark.call(this);
}

new Person(); // "Person"
new Mark(); // "Mark"
new Matteo(); // "Matteo"
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81