Skip to content

Instantly share code, notes, and snippets.

@ElliotChong
Created September 4, 2012 18:13
Show Gist options
  • Save ElliotChong/3624399 to your computer and use it in GitHub Desktop.
Save ElliotChong/3624399 to your computer and use it in GitHub Desktop.
Add inheritance to JavaScript
(function ()
{
if (!Function.prototype.inherit)
{
Function.prototype.inherit = function (p_parent)
{
if (p_parent.constructor == Function)
{
// Normal Inheritance
this.prototype = new p_parent();
this.prototype.constructor = this;
this.prototype.supr = p_parent.prototype;
}
else
{
// Virtual Inheritance
this.prototype = p_parent;
this.prototype.constructor = this;
this.prototype.supr = p_parent;
}
return this;
}
}
if (!Object.prototype.inherit)
{
Object.prototype.inherit = function ()
{
if (arguments.length > 0)
{
this.supr.constructor.apply(this, arguments);
}
else
{
this.supr.constructor.call(this);
}
}
}
})()
/*
Usage:
function Mammal(p_speech)
{
Mammal.prototype.speak = function (p_phrase)
{
if (p_phrase)
{
console.log(p_phrase);
}
}
this.speak(p_speech);
}
function Dog()
{
this.inherit("I'm a dog!");
this.speak("Woof woof!");
}
Dog.inherit(Mammal);
function Cat()
{
Cat.prototype.speak = function ()
{
console.log("Augmenting the ancestor's speak function!");
this.supr.speak.apply(this, arguments);
}
this.inherit("I'm a cat!");
this.speak("Meow!");
}
Cat.inherit(Mammal);
new Dog();
new Cat();
Output:
I'm a dog!
Woof woof!
Augmenting the ancestor's speak function!
I'm a cat!
Augmenting the ancestor's speak function!
Meow!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment