Currently I am reading a book about OO/PB JS. In terms of inheritance a couple of different ways are described.
Below I have pasted two different ways. The second version is used most of the time in the book. I can not understand why, because the first one seems more elegant, as there is no obsolete function F used as in the second version. Can anyone tell me an advantage of the second version or why it even exists?
Version 1:
function Shape() {}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function() {
return this.name;
};
function Triangle(side, height) {
this.side = side;
this.height = height;
}
Triangle.prototype = new Shape();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function() {
return this.side * this.height / 2;
};
var myTriangle = new Triangle(5, 10);
Version 2:
function Shape() {}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function() {
return this.name;
};
function Triangle(side, height) {
this.side = side;
this.height = height;
}
function F() {};
F.prototype = Shape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function() {
return this.side * this.height / 2;
};
var myTriangle = new Triangle(5, 10);