Delegation / Differential Inheritance with Object.create (and RequireJS)

See http://davidwalsh.name/javascript-objects-deconstruction and http://ericleads.com/2013/02/fluent-javascript-three-different-kinds-of-prototypal-oo/

by riddla

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.6/require.min.js"></script>

JavaScript

define('myDelegatePrototype', function () {
    return {
        init: function(who) {
            this.me = who;
        },
        identify: function() {
            return "I am " + this.me + " " + this.sirname();
        }
    };
});

define('myTestObject', ['myDelegatePrototype'], function(myDelegatePrototype) {
    // link objects
    var george = Object.create(myDelegatePrototype);
    george.sirname = function() {
        return 'Washington';
    };
    george.speak = function() {
        alert("Hi, I am " + this.identify() + ".");  
    };
    
    return george;
});

require.config({
    deps: ['myTestObject', 'myDelegatePrototype'],
    callback: function (myTestObject, myDelegatePrototype) {       
        
        myTestObject.init('George');
        myTestObject.speak();
        
        // test method delegation
        console.assert(myDelegatePrototype.isPrototypeOf(myTestObject));
        console.assert(Object.getPrototypeOf(myTestObject) === myDelegatePrototype);
        console.assert(myTestObject.hasOwnProperty('hello') === false);
        console.assert('identify' in myTestObject === true, 'Linked object can call methods of parent');
    }
});