我花了最近几个小时试图找到解决我的问题,但它似乎是无望的。如何从JavaScript中的子类调用父方法?
基本上我需要知道如何从子类调用父方法。 迄今为止我尝试过的所有东西都以不工作或覆盖父方法结束。
我使用下面的代码来设置OOP在javascript:
// 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中完成的。
任何帮助非常感谢,谢谢!
如果你想它调用当前实例的情况下,你必须做'ParentClass.prototype.myMethod.apply()或'ParentClass.prototype.myMethod.call()',像你一样与你的构造函数。 – JMM 2012-08-07 23:40:00
只需添加如果你想用参数调用,他们进入应用程序或调用函数('ParentClass.prototype.myMethod.call(this,arg1,arg2,arg3 ...);') – 2015-05-17 11:47:52
我不理解。如果我调用ParentClass.prototype.myMethod.call(this);从ChildObject的myMethod,我有一个错误“未捕获TypeError:无法读取未定义的属性'调用'。 – zhekaus 2016-03-10 20:58:46