// Simply copying the prototype is more efficient but it has a side effect: because all of the children and parents point to the same object, when a child modifies the prototype, the parents get the changes, and so do the siblings.
// Triangle.prototype.name = 'Triangle';
// Above line changes the name property, so it effectively changes Shape.prototype.name too. If you create an instance using new Shape(), its name property will say "Triangle":
//-----------------------------------------------------------------------------------------------------------------//
// Solution to previous code
// Inheritance: A Temporary Constructor—new F()
function Shape() {
// Empty constructor
}
// Augmenting prototype
Shape.prototype.name = "Shape";
Shape.prototype.toString = function () {
return this.name;
};
function TwoDShape() {
// Empty constructor
}
// Take care of inheritance
function F() {
// Empty temp constructor
}
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
// Augmenting prototype
TwoDShape.prototype.name = "2D Shape";
function Triangle(size, height) {
this.size = size;
this.height = height;
}
// Take care of inheritance
function F() {
// Empty temp constructor
}
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
// Augmenting prototype
Triangle.prototype.name = "Triangle";
Triangle.prototype.getArea = function () {
return this.size * this.height / 2;
};
var t4 = new Triangle(5, 10);
console.log(t4.toString()); // Triangle
console.log(t4.getArea()); // 25
console.log(t4 instanceof Triangle); // true
console.log(t4 instanceof TwoDShape); // true
console.log(t4 instanceof Shape); // true
console.log(t4 instanceof Array); // false
var s = new Shape();
console.log(s.name); // Shape
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.