cool tech graphics

First class dependency objects in ECMAScript Harmony

Filed under:

My favorite perk of Require.JS is how dependencies are sent as arguments to a factory function. Treating dependencies as first class objects makes much more sense to me than polluting the window object - something that happens too much with other dependency management solutions (I'm looking at you, Steal.JS).

I was curious how I might get this functionality with the next generation of JavaScript - namely, ECMAScript Harmony. No browsers implement Harmony's module system just yet, so pardon the pseudocode.

First class dependency objects via Require.JS


define([
'../src/helloworld',
'../lib/jquery',
],
function(helloworld, $){
$('body').html(helloworld.sayIt());
});

In this example, helloworld.js and jquery.js are fully loaded first, then passed as objects named helloworld and $, respectively. Once in the factory function, I have free reign over the dependencies' methods, properties, and prototypes.

First class dependency objects via ECMAScript Harmony


module helloworld from '../src/helloworld.js';
module $ from '../lib/jquery.js';
$('body').html(helloworld.sayIt());

This is the same result as Require.JS - the dependencies are loaded asynchronously (Harmony loads modules at compile time), and the dependencies are nicely encapsulated in their respective first class objects.

As it stands, I find the Require.JS syntax to be more readable. The list of dependencies and their mapping to objects is crystal clear. Since I haven't been able to test ECMAScript Harmony modules in a browser yet, the jury is still out on the pleasures of the new module syntax.

Date posted: February 21, 2012

Comments

it should be noted that in your require.js example, without wrapping jquery in a define that returns jQuery, it does pollute the window object, with window.jQuery.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>, <java>, <php>. The supported tag styles are: <foo>, [foo].
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Metal Toad is an Advanced AWS Consulting Partner. Learn more about our AWS Managed Services

Schedule a Free Consultation

Speak with our team to understand how Metal Toad can help you drive innovation, growth, and success.