Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中从子方法调用父方法。_Javascript_Class - Fatal编程技术网

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

在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

我有一门课叫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.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');
}
…尽管如此,我认为不值得在那里抽象