问题描述
过去几个小时我一直在努力寻找解决我的问题的方法,但似乎毫无希望.
I've spent the last couple of hours trying to find a solution to my problem but it seems to be hopeless.
基本上我需要知道如何从子类调用父方法.到目前为止,我尝试过的所有东西都以要么不起作用要么覆盖父方法而告终.
Basically I need to know how to call a parent method from a child class.All the stuff that I've tried so far ends up in either not working or over-writing the parent method.
我使用以下代码在 javascript 中设置 OOP:
I am using the following code to set up OOP in 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);
我需要先调用父类的方法,然后再在子类中添加一些东西.
I need to call the parent's method first and then add some more stuff to it in the child class.
在大多数 OOP 语言中,只需调用 parent.myMethod()
但我真的无法理解它是如何在 javascript 中完成的.
In most OOP languages that would be as simple as calling parent.myMethod()
But I really cant grasp how its done in javascript.
非常感谢任何帮助,谢谢!
Any help is much appreciated, thank you!
推荐答案
这是它是如何完成的:ParentClass.prototype.myMethod();
或者如果你想在当前实例的上下文中调用它,你可以这样做:ParentClass.prototype.myMethod.call(this)
Or if you want to call it in the context of the current instance, you can do:ParentClass.prototype.myMethod.call(this)
从带有参数的子类调用父方法也是如此:ParentClass.prototype.myMethod.call(this, arg1, arg2, ..)
* 提示:使用 apply()
而不是 call()
将参数作为数组传递.
Same goes for calling a parent method from child class with arguments:ParentClass.prototype.myMethod.call(this, arg1, arg2, ..)
* Hint: use apply()
instead of call()
to pass arguments as an array.
这篇关于如何从javascript中的子类调用父方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!