0

我有一个班级叫人:

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');
}

我想要的是能够从它的子sayHello方法中调用父方法sayHello,如下所示:

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

因此,当我有一个学生实例并在此实例上调用 sayHello 方法时,它现在应该警告“你好”,然后是“嗨,我是学生”。

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

4

1 回答 1

2

你可以做:

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');
}

...虽然,TBH,我认为那里的抽象不值得。

于 2013-04-04T19:37:33.117 回答