想象一下以下场景:
我有两个课程:Parent
和Child
。 Parent有一个方法foo()
。 Child
希望覆盖foo()
,并在foo()
Parent
foo()
内执行foo(){
super.foo();
//do new stuff
}
内所做的任何事情。
在任何其他编程语言中,我会做类似
的事情function Parent( name, stuff ){
this.name = name;
this.stuff = stuff;
}
Parent.prototype = {
foo: function(){
console.log('foo');
}
}
function Child(name, stuff, otherStuff ){
Parent.call(this, name, stuff);
this.otherStuff = otherStuff;
}
Child.prototype = new Parent();
Child.prototype.foo = function(){
???//I want to call my parents foo()! :(
console.log('bar');
}
但是在javascript中没有这样的东西。这是我的代码的简短版本:
Child
我想要实现的是当foo()
调用foobar
的实例时,我可以在控制台中获得{{1}}。
谢谢!
PS:拜托,没有JQuery,PrototypeJS,ExtJs等......这是一个Javascript项目,也是一个学习练习。谢谢。
答案 0 :(得分:1)
简单来说,你可以使用原型并使用call / apply来调用parent函数。
Child.prototype.foo = function(){
Parent.prototype.foo.apply(this, arguments);
console.log('bar');
}
答案 1 :(得分:1)
首先,你的继承实现并不是很好。我提出以下改变:
// Child.prototype = new Parent(); // bad because you instantiate parent here
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
考虑到这一点,我写了这个辅助函数:
function base(object, methodName) {
var proto = object.constructor.prototype;
var args = Array.prototype.slice.call(arguments, 2);
while (proto = Object.getPrototypeOf(proto))
if (proto[methodName])
return proto[methodName].apply(this,args);
throw Error('No method with name ' + methodName + ' found in prototype chain');
}
// usage:
Child.prototype.foo = function(){
base(this, 'foo', 'argument1', 'argument2');
console.log('bar');
};
它比你想要的略多,因为你不必怀疑在继承链中定义方法的位置,它会一直到根并尝试找到方法。我还用祖父母稍微扩展了你的例子以展示这个问题。 foo
方法已从Parent移至祖父母(并且Parent继承自祖父母)。
祖父母演示:http://jsbin.com/iwaWaRe/2/edit
注意:实施基于Google Closure Library对goog.base
的实施。