Created
March 26, 2012 21:54
-
-
Save nyaray/2210045 to your computer and use it in GitHub Desktop.
Simple inheritance demonstration in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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