I have F which inherits from Shape.
F.prototype = Shape.prototype;
F creates new method with name test.
F.prototype.test = function(){return 'test';};
I understand that if I write F.prototype = Shape.prototype; all the methods which I create in F will be available by other class which inheritance from Shape.
What have I done wrong?
Why do I get errors when I execute the code 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 this example when F which inherits from Shape and Triangle created from F
jsFiddle demo woek well
Strictly speaking, you’re not. You are overwriting the
prototypeproperty of theFfunction. To build a real inheritance chain, you would need to useso that Shape’s properties are still available on F instances, but not the other way round (as both prototypes were the same object). So to answer your first question: Yes, you did.
See also Why wouldn't I use Child.prototype = Parent.Prototype rather than Child.prototype = new Parent(); for Javascript inheritance?
That’s simple to explain.
B(which you forgot to declare in your example, but let’s assume it’s a function) is a Function object. You don’t have any properties assigned to it.What you have done is setting it’s prototype property (using the
newkeyword also sets up the prototype chain correctly, but accidentally creates an instance –Object.createis preferred). So now, any instances ofBwill inherit from that prototype object: