// augment Function prototype with "method" method
// which adds a method to the prototype
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
// augment (via new method method) Function with "inherits"
// sets prototype as Object provided along with constructor
Function.method('inherits', function (parent) {
this.prototype = new parent();
var d = {},
p = this.prototype;
this.prototype.constructor = parent;
// also tack on "uber" method to call super/parent
this.method('uber', function uber(name) {
if (!(name in d)) {
d[name] = 0;
}
var f, r, t = d[name], v = parent.prototype;
if (t) {
while (t) {
v = v.constructor.prototype;
t -= 1;
}
f = v[name];
} else {
f = p[name];
if (f == this[name]) {
f = v[name];
}
}
d[name] += 1;
r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
d[name] -= 1;
return r;
});
return this;
});
var Rectangle = function(width, height) {
this.width = width;
this.height = height;
};
Rectangle.method('getName', function() {
return "Rectangle";
});
Rectangle.method('area', function () {
return this.width * this.height;
});
var myRect = new Rectangle(2, 2);
console.log('myRect area is %d', myRect.area()); // returns 4
var Square = function(size) {
this.width = this.height = size;
};
Square.inherits(Rectangle);
Square.method('getName', function() {
return "Square";
});
var mySquare = new Square(4);
console.log('mySquare area is %d', mySquare.area()); // returns 16
console.log(mySquare.getName());
console.log(mySquare.uber('getName')); // calls parent getName()
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.