backbone and underscore are usable in both the browser and nodejs.
they use the following pattern:
(function(){
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = this.Backbone = {};
}
// ...
})();
is this the best way to achieve this?
“Best”? Well, that’s a subjective thing; it’s certainly a good way.
Something you left out that’s quite important is that the function should use
thisas the reference to the global context — what code targeted at browsers would call “window”:That way, it’s possible for the code to “export” symbols:
Another similar trick is to do this:
That has pretty much the same effect.