简体   繁体   中英

Is this the correct way for class inheritance within Javascript?

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'

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM