[英]Calling parent method from child method in Javascript.
I have a class called person: 我有一个叫做人的课:
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
The student class inherits from 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');
}
What I want is to be able to call the parent method sayHello from within it's childs sayHello method, like this: 我想要的是能够从它的childs sayHello方法中调用父方法sayHello,如下所示:
Student.prototype.sayHello = function(){
SUPER // call super
alert('hi, I am a student');
}
So that when I have an instance of student and I call the sayHello method on this instance it should now alert 'hello' and then 'hi, I am a student'. 因此,当我有一个学生实例并且我在这个实例上调用sayHello方法时,它现在应该警告'你好'然后'嗨,我是学生'。
What is a nice elegant and (modern) way to call super, without using a framework? 在不使用框架的情况下,调用超级的优雅和(现代)方式是什么?
You can do: 你可以做:
Student.prototype.sayHello = function(){
Person.prototype.sayHello.call(this);
alert('hi, I am a student');
}
You could also make it a little more generic by doing something like this: 通过这样做,你也可以让它变得更通用:
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');
}
...although, TBH, I don't think it's worth the abstraction there. ......虽然,TBH,我不认为那里的抽象是值得的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.