Warum kann ich eine prototypisierte Methode in Javascript nicht aufrufen?
Ich habe F, das von Shape erbt.
F.prototype = Shape.prototype;
F legt eine neue Methode mit Namenstest an.
F.prototype.test = function(){return 'test';};
Ich verstehe das, wenn ich schreibeF.prototype = Shape.prototype;
Alle Methoden, die ich in F erstelle, werden von anderen Klassen verfügbar sein, die von Shape erben.
Was habe ich falsch gemacht?
Warum erhalte ich Fehler, wenn ich den Code ausführe?alert(B.test());
?
function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};
var F = function(){};
F.prototype = Shape.prototype;
F.prototype.test = function(){return 'test';};
function Triangle(side, height) {
this.side = side;
this.height = height;
}
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
var my = new Triangle(5, 10);
alert(my.toString());
var Second_class = function(){};
Second_class.prototype = Shape.prototype;
B.prototype = new Second_class();
alert(B.test());
in diesem Beispiel wennF
was erbt vonShape
undTriangle
erstellt vonF
jsFiddle Demo Woek gut