i am new to JS and quite confused in this topic. now i am reading a book and it says :-
where all prototypes point to the same object and the parents get children's properties, is to use an intermediary to break the chain. The intermediary is in the form of a temporary constructor function.
Creating an empty function F() and setting its prototype to the prototype of the parent constructor, allows you to call new F() and create objects that have no properties of their own, but inherit everything from the parent's prototype.
Here is the code.
function Shape() {
}
// augment prototype
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function () {
return this.name;
};
function TwoDShape() {
};
// take care of inheritance
// Creating a Temporary constructor Function
var F = function () {
};
// Then Setting its prototype to Parent's Prototype.
F.prototype = Shape.prototype;
// Allows to call a function
TwoDShape.prototype = new F();
//Settubg cobstryctir
TwoDShape.prototype.constructor = TwoDShape;
// augment prototype
TwoDShape.prototype.name = '2D shape';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
var F = function() {
};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
// augment prototype
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function () {
return this.side * this.height / 2;
};
var my = new Triangle(5, 10);
console.log(my.getArea());
Now i am confused that line
allows you to call new F() and create objects that have no properties of their own, but inherit everything from the parent's prototype.
Triangle.prototype = new F();
means when we create a triangle obj it's prototype points to new Object right? and then
F.prototype = Shape.prototype;
Which means f prototype points to Shape prototype.. so indirectly the new object of triangle is using shape prototype. But what is the use?? Why are doing this? Please bear with me as i am a learner. thanks.