首页 > 解决方案 > 如何在子原型中重写父原型函数?

问题描述

我正在学习 JS 中的原型,我在尝试在我的子原型中重写我的父原型函数时遇到了麻烦。

在下面的代码中,我试图从我的 Personn 类重写函数表示,以便也显示新的 Etudiant 属性“etablissement”。

function Personne(nom, age, sexe){
    this.nom = nom;
    this.age = age;
    this.sexe = sexe;
}

Personne.prototype.presentation = function() {
    return 'Bonjour, je suis ', this.nom + ', ' + this.sexe + ' de ' + this.age + ' ans.';
}

function Etudiant(nom, age, sexe, etablissement){
    Personne.call(this, [nom, age, sexe]);
    this.etablissement = etablissement;
}

Etudiant.prototype = Object.create(Personne.prototype);
Etudiant.prototype.constructor = Etudiant;

Etudiant.prototype.presentation = function (){
    return Personne.prototype.presentation.call(this) + ' Je travaille au ' + this.etablissement + '.';
};

let patrick = new Etudiant('patrick', 26, 'etoile de mer', 'Club');
console.log(patrick.presentation()); // this displays 'patrick,5651,etoile de mer, undefined de undefined ans. Je travaille au Club.'

标签: javascriptinheritanceprototype

解决方案


问题在这里:

Personne.call(this, [nom, age, sexe]);

使用call,您传递离散参数,而不是参数数组。将其更改为 use apply,它确实需要一个数组(或任何类似数组):

Personne.apply(this, [nom, age, sexe]);

或使参数离散:

Personne.call(this, nom, age, sexe);

现场示例:

function Personne(nom, age, sexe){
    this.nom = nom;
    this.age = age;
    this.sexe = sexe;
}

Personne.prototype.presentation = function() {
    return 'Bonjour, je suis ', this.nom + ', ' + this.sexe + ' de ' + this.age + ' ans.';
}

function Etudiant(nom, age, sexe, etablissement){
    Personne.call(this, nom, age, sexe);
    this.etablissement = etablissement;
}

Etudiant.prototype = Object.create(Personne.prototype);
Etudiant.prototype.constructor = Etudiant;

Etudiant.prototype.presentation = function (){
    return Personne.prototype.presentation.call(this) + ' Je travaille au ' + this.etablissement + '.';
};

let patrick = new Etudiant('patrick', 26, 'etoile de mer', 'Club');
console.log(patrick.presentation()); // this displays 'patrick,5651,etoile de mer, undefined de undefined ans. Je travaille au Club.'


旁注:如果您要使用构造函数和属性,在现代 JavaScript (ES2015+) 中,您可以使用语法prototype更轻松地做到这一点:class

class Personne {
    constructor(nom, age, sexe){
        this.nom = nom;
        this.age = age;
        this.sexe = sexe;
    }

    presentation() {
        return 'Bonjour, je suis ', this.nom + ', ' + this.sexe + ' de ' + this.age + ' ans.';
    }
}

class Etudiant extends Personne {
    constructor(nom, age, sexe, etablissement) {
        super(nom, age, sexe);
        this.etablissement = etablissement;
    }

    presentation() {
        return super.presentation() + ' Je travaille au ' + this.etablissement + '.';
    }
}

let patrick = new Etudiant('patrick', 26, 'etoile de mer', 'Club');
console.log(patrick.presentation()); // this displays 'patrick,5651,etoile de mer, undefined de undefined ans. Je travaille au Club.'

它有效地创建了相同的东西(有一些细微的区别,主要的区别是构造函数不能被称为普通函数——你通常不希望它们如此)。重要的是,它仍然使用原型继承、构造函数和prototype属性;语法只是使设置变得更容易,并且更具声明性。


推荐阅读