The*_*onk 31 javascript inheritance prototype
假设我有这样一个类:
function Widget() {
this.id = new Date().getTime();
// other fields
}
Widget.prototype = {
load: function(args) {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
从这个类我创建了一些继承相同原型但有一些添加方法的其他类.我想要做的是能够在子类中定义一个load()方法,该方法首先调用父方法,然后执行一些代码.就像是:
SpecialWidget.prototype = {
load: function(args) {
super.load(args);
// specific code here
}
}
Run Code Online (Sandbox Code Playgroud)
我知道Javascript中没有超级关键字,但必须有办法做到这一点.
kar*_*m79 40
你可以像这样模拟它:
SpecialWidget.prototype = {
load: function(args) {
Widget.prototype.load.call(this, args);
// specific code here
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以创建自己的超级属性,如下所示:
SpecialWidget.prototype.parent = Widget.prototype;
SpecialWidget.prototype = {
load: function(args) {
this.parent.load.call(this,args);
// specific code here
}
}
Run Code Online (Sandbox Code Playgroud)