在Javascript中从子方法调用父方法。
我有一门课叫person:在Javascript中从子方法调用父方法。,javascript,class,Javascript,Class,我有一门课叫person: function Person() {} Person.prototype.walk = function(){ alert ('I am walking!'); }; Person.prototype.sayHello = function(){ alert ('hello'); }; 学生类继承自person: function Student() { Person.call(this); } Student.prototype = Object
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
学生类继承自person:
function Student() {
Person.call(this);
}
Student.prototype = Object.create(Person.prototype);
// override the sayHello method
Student.prototype.sayHello = function(){
alert('hi, I am a student');
}
我想要的是能够从它的childs sayHello方法中调用父方法sayHello,如下所示:
Student.prototype.sayHello = function(){
SUPER // call super
alert('hi, I am a student');
}
function Student() {
this._super = Person;
this._super.call(this);
}
...
Student.prototype.sayHello = function(){
this._super.prototype.sayHello.call(this);
alert('hi, I am a student');
}
因此,当我有一个student实例,并且我在这个实例上调用sayHello方法时,它现在应该提醒“hello”,然后是“hi,我是学生”
在不使用框架的情况下,调用super的优雅(现代)方式是什么?您可以:
Student.prototype.sayHello = function(){
Person.prototype.sayHello.call(this);
alert('hi, I am a student');
}
您还可以通过执行以下操作使其更加通用:
Student.prototype.sayHello = function(){
SUPER // call super
alert('hi, I am a student');
}
function Student() {
this._super = Person;
this._super.call(this);
}
...
Student.prototype.sayHello = function(){
this._super.prototype.sayHello.call(this);
alert('hi, I am a student');
}
…尽管如此,我认为不值得在那里抽象