JSFiddle - React, Tailwind, and code Playground

by Couto

HTML

<div id="output"></div>

JavaScript

var print = function(s) { document.getElementById('output').innerHTML += s+'<br>';};

//Class A
var A = function() {};
A.prototype.doSomething = function() { print('A worked'); };

//Class B
var B = function(a) { this.a = a; };
B.$deps = ['a'];
B.prototype.doSomething = function() { 
    print('B worked'); 
    this.a.doSomething();
};

//Class C
var C = function() {};
C.prototype.doSomething = function() { print('C worked'); };
    
//Class D
var D = function(b,c) { this.b = b; this.c = c;};
D.$deps = ['b','c'];
D.prototype.doSomething = function() {
    print('D worked');
    this.b.doSomething();
    this.c.doSomething();
};


var dependencyMap =
{
    "a" : A,
    "b" : B,
    "c" : C,
    "d" : D
};
    
//instanciate an object like new does but with array of args
function newObject(func, args) { 
  // create a new object with its prototype assigned to func.prototype
  var object = Object.create(func.prototype);
 
  // invoke the constructor, passing the new object as 'this'
  // and the rest of the arguments as the arguments
  func.apply(object, args);
 
  // return the new object
  return object;
}

var DICreate = function(constructor) {
    if( constructor.$deps ) {
        var deps = constructor.$deps;
        if( deps.length == 0 ) {
            return new constructor();
        }
        else {
            var depInstances = [];
            for( var i = 0 ; i < deps.length; i++ ) {
                depInstances[i] = DICreate(dependencyMap[deps[i]]);
            }
            return newObject(constructor,depInstances);
        }
     }
     else {
        return new constructor();
     }
};
    
print('starting');
var a = DICreate(D);
a.doSomething();