2012-03-05 32 views
1

関数内の関数を上書き/上書きできますか? 私はコードを変更できない機能を持っています。私はその方法の1つを変更したいと思います。私は、次のことを試してみたが、それはまだ「親のinit」を警告関数内の関数をオーバーライド/上書きする

parent = function(arg){ 
    this.init = function(){ 
     alert("parent init") 

    } 
    this.other = function(){ 
     alert('i just do this')   
    } 
    // lots of other code that I would like not to have to copy paste 

    this.init(); 
} 

child = function(arg){ 
    this.init = function(){ 
     alert("child init") 
    } 
}   

child.prototype = new parent(); 
child.prototype.init = function(){ 
    alert("another child init attempt") 
} 
child.init = function(){ 
    alert("another another child init attempt") 
} 

var x = new child(); 
+0

これは、割り当てられた直後に 'this.init'を呼び出すからです。自然に使用される値になります。後で 'x.init()'を呼び出すと、 "child init"が得られます。 –

+0

また、 'parent'が' new child() 'によって呼び出されることを期待している必要がありますが、これはプロトタイプ継承の仕組みではありません。 – clockworkgeek

答えて

0

はフィドルを参照してください:

child.prototype = new parent(); 
:あなたが実際に新しい親を作成しているので、それは親から警告され http://jsfiddle.net/yXguc/

子initは独自のinitを呼び出さないため何も警告しません。親のコンストラクタを実行するには、それを手動で呼び出す必要があります。

var x = new child(); 
関連する問題