Skip to content

Instantly share code, notes, and snippets.

@daveespionage
Forked from ElliotChong/addInheritance.js
Created September 7, 2012 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daveespionage/3666325 to your computer and use it in GitHub Desktop.
Save daveespionage/3666325 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