【问题标题】:Can a javascript object override its parent method and call it in that method?javascript 对象可以覆盖其父方法并在该方法中调用它吗?
【发布时间】:2013-11-18 15:21:44
【问题描述】:

想象以下场景:

我有两个班级:ParentChild。 Parent 有一个方法foo()Child 想要覆盖 foo(),并在其中执行 foo()Parentfoo() 中所做的任何事情。

在任何其他编程语言中,我都会做类似的事情

foo(){
  super.foo();
  //do new stuff
}

但在 javascript 中没有这样的东西。这是我的代码的简短版本:

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');

}

我想要实现的是,当Child 的实例调用foo() 时,我可以在控制台中获得foobar

谢谢!

PS:请不要使用 JQuery、PrototypeJS、ExtJs 等……这是一个 Javascript 项目,也是一个学习练习。谢谢。

【问题讨论】:

标签: javascript


【解决方案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 移至 Grandparent(并且 Parent 继承自 Grandparent)。

祖父母演示:http://jsbin.com/iwaWaRe/2/edit

注意:该实现大致基于 Google Closure Library 的 goog.base 实现。

【讨论】:

    【解决方案2】:

    很简单,你可以使用原型,使用call/apply来调用parents函数。

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

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

    【讨论】:

    • 不如 super.foo() 漂亮,但它确实有效。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2012-06-10
    相关资源
    最近更新 更多