Although I have some working experience with jQuery and JavaScript I still find it difficult to understand prototypal inheritance. Hence I have started reading Stoyan Stefanov's book entitled "Object Oriented JavaScript". However I ran into problems while solving the following exercises from the book:
- Create an object called
shape
that has atype
property and agetType
method. - Define a
Triangle
constructor function whose prototype is shape. Objects created withTriangle
should have three own properties:a
,b
andc
representing the sides of a triangle. - Add a new method to the prototype called
getPerimeter
.
Test your implementation with this code:
var t = new Triangle(1, 2, 3);
t.constructor; // Triangle(a, b, c)
shape.isPrototypeOf(t); // true
t.getPerimeter(); // 6
t.getType(); // "triangle"
I have tried to solve this problem with the following code:
shape = {
type : "",
getType: function(){
return this.type;
}
};
function Triangle(a, b, c) {
}
Triangle.prototype = shape;
However it does not seem to work as expected. How would you solve this problem? Please explain it in detail. I would really like to understand prototypal inheritance.