2017-02-16 5 views
1

Ich habe den folgenden Code, wo gibt es zwei Funktionen a, c und c erbt von a.Javascript util.herherits Problem beim Aufruf abgeleiteter Klassenfunktionen

function a(){ 
    console.log("constructor-a"); 
} 

a.prototype.fun1 = function(){ 
    console.log("a-fun1"); 
} 
a.prototype.fun2 = function(){ 
    console.log("a-fun2"); 
} 


function c(){ 
    c.super_.call(this) 
    console.log("constructor-c"); 
} 

c.prototype.fun5 = function(){ 
    console.log("c-fun1"); 
} 
c.prototype.fun6 = function(){ 
    console.log("c-fun2"); 
} 
util.inherits(c,a); 

var X = new c(); 
console.log("X instanceof a", X instanceof a); 
console.log("X instanceof a", X instanceof c); 

Da C wird aus einem vererben, die Funktionen von sowohl C als auch a sollte von einem Objekt von C, jedoch in diesem Fall ausführbar sind die Ausgänge wie folgt:

X.fun1() --> a-fun1 
X.fun2() --> a-fun2 
X.fun5() --> TypeError: X.fun5 is not a function 
X.fun6() --> TypeError: X.fun6 is not a function 
+0

"util.inherits" muss vor Zuweisungen an den Prototyp aufgerufen werden. – Bergi

Antwort

1

Do util.inherits(c,a) zuerst und dann erstellen fun5 und fun6.

function c(){ 
    c.super_.call(this) 
    console.log("constructor-c"); 
} 

util.inherits(c,a); 

c.prototype.fun5 = function(){ 
    console.log("c-fun1"); 
} 
c.prototype.fun6 = function(){ 
    console.log("c-fun2"); 
} 

Dies ist wegen der sehr Implementierung von util.inherits. Diese Funktion wird den Prototyp von c mit dem des übergeordneten Elements neu zuweisen, anstatt zu verschmelzen. Lassen Sie also util.inherits den b Prototyp zuerst c zuweisen und fügen Sie dann zusätzliche Funktionen hinzu, die Sie wünschen.

Verwandte Themen