【发布时间】:2012-08-04 23:58:14
【问题描述】:
过去几个小时我一直在试图找到解决问题的方法,但似乎没有希望。
基本上我需要知道如何从子类调用父方法。 到目前为止,我尝试过的所有东西都以无法正常工作或覆盖父方法而告终。
我正在使用以下代码在 javascript 中设置 OOP:
// SET UP OOP
// surrogate constructor (empty function)
function surrogateCtor() {}
function extend(base, sub) {
// copy the prototype from the base to setup inheritance
surrogateCtor.prototype = base.prototype;
sub.prototype = new surrogateCtor();
sub.prototype.constructor = sub;
}
// parent class
function ParentObject(name) {
this.name = name;
}
// parent's methods
ParentObject.prototype = {
myMethod: function(arg) {
this.name = arg;
}
}
// child
function ChildObject(name) {
// call the parent's constructor
ParentObject.call(this, name);
this.myMethod = function(arg) {
// HOW DO I CALL THE PARENT METHOD HERE?
// do stuff
}
}
// setup the prototype chain
extend(ParentObject, ChildObject);
我需要先调用父类的方法,然后在子类中添加一些东西。
在大多数 OOP 语言中,这就像调用 parent.myMethod() 一样简单
但我真的无法理解它是如何在 javascript 中完成的。
非常感谢任何帮助,谢谢!
【问题讨论】:
标签: javascript oop methods parent