簡體   English   中英

javascript對象可以覆蓋其父方法並在該方法中調用它嗎?

[英]Can a javascript object override its parent method and call it in that method?

想象一下以下場景:

我有兩個班: ParentChild Parent有一個方法foo() Child想要覆蓋foo() ,並在Parentfoo()foo()

在任何其他編程語言中,我會做類似的事情

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項目,也是一個學習練習。 謝謝。

簡單來說,你可以使用原型並使用call / apply來調用parent函數。

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

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

首先,你的繼承實現並不是很好。 我建議進行以下更改:

// 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實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM