我正在用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
,您传递离散参数,而不是参数数组。可以更改为使用call
,它确实需要一个数组(或任何类似数组的数组):
apply
或使参数离散:
apply
实时示例:
Personne.apply(this, [nom, age, sexe]);
旁注:如果要使用构造函数和Personne.call(this, nom, age, sexe);
属性,在现代JavaScript(ES2015 +)中,可以使用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
它实际上创建了相同的东西(有一些细微的差别,主要是构造函数不能被称为普通函数,通常您不希望它们成为函数)。重要的是,它仍然使用原型继承,构造函数和class
属性。语法使设置起来更容易,并且更具声明性。