Skip to content

Instantly share code, notes, and snippets.

@supasympa
Created July 14, 2011 14:36
Show Gist options
  • Save supasympa/1082572 to your computer and use it in GitHub Desktop.
Save supasympa/1082572 to your computer and use it in GitHub Desktop.
My example of prototypal inheritance in Javascript for when I forget!
/*
An example of prototypal inheritance in Javascript for when I forget!
*/
console.log('> inheritance.js');
function main(){
console.log('start main.');
var Human = function(age, name){
console.log('creating human');
this.name = name;
this.age = age;
};
Human.prototype.getInfo = function(){
return ['My name is ', this.name, ' and a I am ', this.age, ' years old.'].join('');
};
Human.prototype.sayHello = function(id){
console.log('Human.writeName');
var el = document.getElementById(id);
console.log(el);
var innerEl = document.createElement('p');
innerEl.innerHTML = this.getInfo();
el.appendChild(innerEl);
};
/* /////////////////////////////////////////////// */
var Adult = function(age, name, gender){
console.log('creating Adult');
this.name = name;
this.age = age;
this.gender = gender;
};
Adult.prototype = new Human();
Adult.prototype.constructor = Adult;
Adult.prototype.getInfo = function(){
return ['My name is ', this.name, ' and a I am ', this.age, ' years old and a ' , this.gender].join('');
};
var adult = new Adult(20, 'Old Person', 'male');
adult.sayHello('infowindow');
var kid = new Human(9, 'Young Person');
kid.sayHello('infowindow');
console.log('adult ', adult.constructor);
console.log('kid ', kid.constructor);
console.log('end main.');
}
window.onload = function(){
console.log('document.load.');
main();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment