Created
October 27, 2012 19:03
-
-
Save netpoetica/3965707 to your computer and use it in GitHub Desktop.
A useful example of prototypal multiple inheritance and how the Prototype chain works
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
// Useful example of inheritance. We will demonstrate multiple | |
// levels of inheritance here - objects inheriting from objects | |
// inheriting from objects :) | |
// Based on example I found here: http://atomicrobotdesign.com/blog/javascript/a-bit-more-on-javascript-prototypes/comment-page-1/#comment-83258 | |
function Person(name, city, job) { | |
this.name = name; | |
this.city = city; | |
this.job = job; | |
} | |
Person.prototype = { | |
constructor: Person, | |
getName: function() { | |
console.log('Hi, my name is ' + this.name); | |
}, | |
getCity: function() { | |
console.log('I live in ' + this.city); | |
}, | |
getJob: function() { | |
console.log('My job is ' + this.job); | |
}, | |
getGender: function(){ | |
console.log("I'm a " + this.gender); | |
} | |
} | |
function Man(name, city, job){ | |
this.name = name; | |
this.city = city; | |
this.job = job; | |
} | |
Man.prototype = new Person(); | |
Man.prototype.gender = 'male'; | |
function SuperMan(name, city){ | |
this.name = name; | |
this.city = city; | |
} | |
SuperMan.prototype = new Man(); | |
SuperMan.prototype.job = 'hero'; | |
function God(name){ | |
this.name = name; | |
} | |
God.prototype = new SuperMan(); | |
God.prototype.gender = 'hermaphrodite, like all Gods!'; | |
God.prototype.city = 'the entire world'; | |
// Overwrite a function to say what we like | |
God.prototype.getCity = function(){ | |
console.log('I hold domain over ' + this.city); | |
} | |
God.prototype.job = 'creator'; | |
var keith; | |
keith = new Person('Keithie', 'NJ', 'Webbie'); | |
console.log(keith); | |
keith.getName(); | |
keith.getCity(); | |
keith.getJob(); | |
keith.getGender(); | |
keith = new Man('Keith', 'Lake Hi', 'Developer'); | |
console.log(keith); | |
keith.getName(); | |
keith.getCity(); | |
keith.getJob(); | |
keith.getGender(); | |
keith = new SuperMan('The Krusad0r', 'NY'); | |
console.log(keith); | |
keith.getName(); | |
keith.getCity(); | |
keith.getJob(); | |
keith.getGender(); | |
keith = new God('The Almighty K'); | |
console.log(keith); | |
keith.getName(); | |
keith.getCity(); | |
keith.getJob(); | |
keith.getGender(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment