2012-03-05 234 views
1

您可以覆盖/覆盖功能内的功能吗? 我有一个函数,我不能更改代码。我想改变它的一种方法。我试过以下,但仍提醒“家长初始化”覆盖/覆盖功能内的功能

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”。 – 2012-03-05 23:04:31

+0

另外,你必须期望''parent'被'new child()'调用,但这不是原型继承的工作原理。 – clockworkgeek 2012-03-05 23:41:25

回答

0

见琴:http://jsfiddle.net/yXguc/

它是由父母报警,因为你实际上是在创建一个新的父:

child.prototype = new parent(); 

子init不会提醒任何事情,因为它不会调用它自己的init。如果你想要父母的构造函数被执行,你必须手动调用它。

var x = new child();