0

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);
JShinigami
  • 7,317
  • 3
  • 14
  • 22
  • 1
    `new F` is totally outdated. Use `Triangle.prototype = Object.create(Shape.prototype)`. And throw that book away if it doesn't mention this anywhere. – Bergi Mar 15 '17 at 07:50
  • 1
    see also [A temporary constructor New F()](http://stackoverflow.com/q/33914138/1048572) (apparently that book grew another 2 years older since then) – Bergi Mar 15 '17 at 07:52
  • @Bergi thanks for your comment. the book does not mention Object.create anywhere (published january 2017!). seems that amazon reviews can't be trusted always. anyway, I will read through the other linked stackoverflow questions. – JShinigami Mar 16 '17 at 06:40
  • I can only hope they confused "published" with "printed", but that sounds worrying indeed. – Bergi Mar 16 '17 at 07:11

0 Answers0