supasympa
7/14/2011 - 2:36 PM

My example of prototypal inheritance in Javascript for when I forget!

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();
};