【问题标题】:Is this the correct way for class inheritance within Javascript?这是 Javascript 中类继承的正确方法吗?
【发布时间】:2015-07-16 08:31:09
【问题描述】:

有人可以确认下面的脚本是否确实是 Javascript 中类继承的正确方法吗?

错误的方式

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'

正确的方式

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'

【问题讨论】:

  • 你的代码打印undefined
  • 您要打印哪个变量名?函数本身的名称?
  • 这些名称是变量,在函数解析后分配。它们持有一个匿名函数作为它们的值——但这与函数名不同。另见:kangax.github.io/nfe
  • 我编辑了,我的问题。

标签: javascript class instanceof classname


【解决方案1】:

这对我有用:

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"

【讨论】:

  • 感谢您的贡献,您能回答新问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 2016-11-21
相关资源
最近更新 更多