Skip to content

Instantly share code, notes, and snippets.

@nyaray
Created March 26, 2012 21:54
Show Gist options
  • Save nyaray/2210045 to your computer and use it in GitHub Desktop.
Save nyaray/2210045 to your computer and use it in GitHub Desktop.
Simple inheritance demonstration in Javascript
// A "class"
function MyEpicEntity(name)
{
if(name)
{
this.name = name;
}
this.epic = true; // obvsly...
}
// Create the prototype, an object with one sole attribute named sayName that happens to be a function
MyEpicEntity.prototype =
{
sayName: function()
{
console.log("MyEpicEntity with name: " + this.name);
}
};
// Since we replaced the prototype with a newly created object, we need to correct its constructor reference
// to its intended value.
MyEpicEntity.prototype.constructor = MyEpicEntity;
// A "class" that inherits from MyEpicEntity
function MyAwesomeEntity(name, level)
{
// Call our parent constructor
MyEpicEntity.call(this, name);
this.awesomeLevel = level;
}
// Set up the inheritance and fix the constructor reference
MyAwesomeEntity.prototype = new MyEpicEntity();
// Add a method to the prototype of MyAwesomeEntity
MyAwesomeEntity.prototype.getLevel = function()
{
return (this.awesomeLevel > 9000)? "It's over 9000!!!11" : this.awesomeLevel;
};
MyAwesomeEntity.prototype.constructor = MyAwesomeEntity;
// You are now free to create new "instances" of MyAwesomeEntity while reaping the benefits of having implemented
// MyEpicEntity
var mae = new MyAwesomeEntity("Jim-Bob Bobson", 5);
console.log(mae.getLevel()); // 5
mae.sayName(); // "MyEpicEntity with name: Jim-Bob Bobson"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment