gpt4 book ai didi

javascript - 这是 Javascript 中类继承的正确方法吗?

转载 作者:行者123 更新时间:2023-11-28 19:14:56 24 4
gpt4 key购买 nike

有人可以确认下面的脚本是否确实是 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'

最佳答案

这对我有用:

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"

关于javascript - 这是 Javascript 中类继承的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30072757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com