在Javascript中从子方法调用父方法

Calling parent method from child method in Javascript.

本文关键字:调用 方法 子方法 Javascript      更新时间:2023-09-26

我有一个类叫person:

function Person() {}
Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

student类继承自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');
}

我想要的是能够从它的子sayHello方法中调用父方法sayHello,像这样:

Student.prototype.sayHello = function(){
      SUPER // call super 
      alert('hi, I am a student');
}

所以当我有一个student实例并且我在这个实例上调用sayHello方法时它现在应该提示'hello'然后是'hi, I am a student'

在不使用框架的情况下,调用super的优雅(现代)方式是什么?

你可以这样做:

Student.prototype.sayHello = function(){
    Person.prototype.sayHello.call(this);
    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');
}

…虽然,老实说,我不认为这是值得抽象的。