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
  • 14,724
  • 18
  • 73
  • 98

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
  • 17,408
  • 7
  • 58
  • 80