在Javascript中从子方法调用父方法
Calling parent method from child method in Javascript.
我有一个类叫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');
}
…虽然,老实说,我不认为这是值得抽象的。
相关文章:
- 未捕获错误:无法在初始化之前调用方法;
- 通过ajax从客户端调用C#方法来执行C#方法
- 如何避免在angular上多次调用方法;s ng重复
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 从window.onbeforeunload调用方法背后的代码
- 当输入字段为空时,如何在angular中调用方法
- 函数调用方法有什么用
- 多次调用方法后返回相同promise的模式
- 当从Chrome扩展动态注入JS时,从onload()内部调用方法
- 茉莉花 - 未调用方法
- jQuery如何在原型中调用方法
- ng显示“;调用方法“;不起作用
- Odoo销售点如何访问模型并使用JS调用方法
- 从React调用方法.JS州
- TinyMCE验证给出错误:无法调用方法'getContent'的未定义
- 向模板实例变量传递调用方法调用的结果时出现异常
- 如何在对象中调用方法
- 检查对话框是否为 Open 会引发“初始化前无法在对话框上调用方法”错误
- 在输入类型提交按钮上调用 C# 方法
- 通过类选择器单独调用方法