Inheritance

by sym3tri

HTML

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <div id="out"></div>
    </body>
</html>

JavaScript

function print(txt) {
    var outDiv = document.getElementById('out');
    outDiv.innerHTML += '<br/><br/>' + txt;
}

///////////////////////////////////////////////
// 1. Every object has a constructor property, which is a reference to the function that created the object
// 2. Every function has a prototype property
// 3. Every function's prototype property is set to an empty object upon definition
// 4. When an object property is accessed and doesn't exist, the interpreter looks for it via hidden prototype link
// 5. If property exists on object and prototype, the own property takes precedence over the prototype's 
// 6. prototype.constructor is not reliable 
// 7. The prototype chain is live WITH THE EXCEPTION of when you completely replace the prototype object 
// 8. __proto__ is a property of the instances, whereas prototype is a property of the constructor functions
// 9. When you overwrite the prototype, it is a good idea to reset the constructor property.
///////////////////////////////////////////////

var inherit = (function () {
    var F = function () {};
    return function (C, P) {
        F.prototype = P.prototype; 
        C.prototype = new F(); 
        C.uber = P.prototype; 
        C.prototype.constructor = C;
    }
}());


// Person objects
function Person(n) {
    if (n) {
        this.name = n;
    }
}

Person.prototype.name = 'nameless person';
Person.prototype.toString = function() {
   print('name: ' + this.name);
};
Person.prototype.speak = function() {
    print('hello i am ' + this.name);
};

// Workers
function Worker(n, t) {
    if (n) {
        this.name = n;
    }
    if (t) {
        this.title = t;
    }
}

inherit(Worker, Person);
Worker.prototype.name = 'nameless worker';
Worker.prototype.toString = function() {
    this.constructor.uber.toString.call(this);
    print('title: ' + this.title);
}


// tests

var bob = new Person('Bobby Brown');
bob.toString();

var me = new Worker('ed', 'hacker');
me.toString();
me.speak();