Managing dependencies in Javascript

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at:

All this work just to avoid calling “new”? This should be read as a criticism of the object oriented paradigm. Interesting:

AngularJS goes a little bit further by giving us something called factory. We register our dependencies there, and they are magically available in our controllers. For example:

myModule.factory(‘greeter’, function($window) {
return {
‘greet’: function(text) {
function MyController($scope, greeter) {
$scope.sayHello = function() {
greeter.greet(‘Hello World’);
In general, this approach simplifies our job. We don’t have to use a function like require to fetch the dependency. All we have to do is to type the right words in the arguments’ list.

Ok, these two ways of dependency injection work, but they are bound to a specific style of code writing. In the future, I would like to see frameworks that eliminate this constraint. It will be much elegant if we are able to apply metadata during the variables’ definition. The language right now doesn’t offer such capabilities. It will be nice if the following is possible:

var router:;
Placing the dependency along with the variable’s definition means that we will perform the injection only if needed. RequireJS and AngularJS for example work on a functional level. So, you may use a module only in specific cases, but the initialization and its injection happen every time. There is also a specific place where we have to define our dependencies. We are bound to that.