Skip to content

Instantly share code, notes, and snippets.

@julienrf
Created August 7, 2014 07:02
Show Gist options
  • Save julienrf/06bfb0d331ed126b60c4 to your computer and use it in GitHub Desktop.
Save julienrf/06bfb0d331ed126b60c4 to your computer and use it in GitHub Desktop.
Dependency injection in JavaScript
/* A basic implementation of bar */
define(function () {
return {
plop: function () { alert('bar implementation'); }
}
});
/* An alternative implementation of bar */
define(function () {
return {
plop: function () { alert('baz implementation'); }
}
});
/*
* foo is a module that depends on a bar module.
* Note that the dependency is modeled as a parameter of the function returned by the module definition.
*/
define(function () {
return function (bar) {
return bar.plop()
}
});
/* The end-user wires dependencies */
require(['foo', 'baz'], function (fooProvider, bazProvider) {
var baz = bazProvider();
var foo = fooProvider(baz);
})
@pauldijou
Copy link

It works because both bar.js and baz.js have the same API. It's like having interfaces and implementations. And in this case, you are right, it works fine.

But in my case, for Prolyfill, the fact is that implementations were created before the interface (aka the spec) and so they all have more or less different APIs. You need a way to normalize that if you want to use any of them.

Also, it's not only about dependency but also about polyfill: if the global context already has the feature, do nothing, otherwise, create an implementation. You can only do that at runtime.

@julienrf
Copy link
Author

julienrf commented Aug 7, 2014

Ok, indeed if several implementations have a different API the problem is not the same :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment