javascript对象可以覆盖其父方法并在该方法中调用它吗?

时间:2013-11-18 15:21:44

标签: javascript

想象一下以下场景:

我有两个课程:ParentChild。 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项目,也是一个学习练习。谢谢。

2 个答案:

答案 0 :(得分:1)

简单来说,你可以使用原型并使用call / apply来调用parent函数。

Child.prototype.foo = function(){
  Parent.prototype.foo.apply(this, arguments);
  console.log('bar');
}

看看:http://jsfiddle.net/J4wHW/

答案 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的实施。