OOP Dependency Inversion Principle I made an example for learning Dependency inversion principle in JavaScript OOP programming .

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function textHandler(){

    this.printRedbox = function( ){
        return ' Red Box text ';
    }

    this.printBluebox = function( ){
        return ' Blue Box text ';
    }
};


function htmlHandler( handler ){

    var block = [],
        box  = document.getElementById('container');

    this.boxContentHandler =  handler ;

    this.setType = function( handler ){
        this.boxContentHandler = handler
    };

    this.appendBlock = function( html ){

        block.push( html );
        box.innerHTML = block.join('');
    };

    this.printBox = function ( action ){

        var title = this.printTitle() ,
            text  = this.boxContentHandler[ 'print'+ action.ucfirst() ](),
            html  = '&lt;div class="box '+ action.replace('box','') +'"&gt;'
                        +   title + text
                    +'&lt;/div&gt;' ;

        this.appendBlock( html );
    };

    this.printTitle = function( ) {
            return 'Title ' + block.length + ' &lt;br /&gt;';
    };
};


Here I am doing the action handling part    

var htmlHandle = new htmlHandler(  new textHandler()  );

document.getElementById('bluebox').addEventListener( 'click', function(){
    htmlHandle.printBox(  this.id );
},false );            

document.getElementById('redbox').addEventListener( 'click', function(){
    htmlHandle.printBox(  this.id );
},false );  


I would like to know, is there a way to make it better. Did I miss anything here ?
This is a decent way to implement Dependency Inversion, from the standpoint of your implementing classes. The only improvements I would recommend is to find a good class library that does the lookup of dependencies for you.

Really Inversion of Control/Dependency Inversion involves several parts:


Writing your classes so that they receive their dependencies via one of three methods:

Constructor injection (like you have) new Foo(x)
Property injection a.foo = b
Setter injection a.setFoo(b)

An object factory that can turn a class name in the form of a String into a new object
An dependency resolver that does the lookup of dependencies and injects them into a new object
A "container" object allowing you to configure your dependencies and wire your classes together


I've created Hypodermic for this purpose, though I think it should be refactored to separate the "container" from the "dependency resolver" functionality. I would be interested in finding out if there are other Dependency Injection libraries out there for JavaScript.