如何在子原型中重写父原型函数?



我正在用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.'

问题就在这里:

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

使用call,您可以传递离散参数,而不是参数数组。要么将其更改为使用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.'


旁注:如果你打算使用构造函数和prototype属性,在现代JavaScript(ES2015+)中,你可以用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属性;语法只是使设置更容易,并且更具声明性。

最新更新