2

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?

noop
  • 237
  • 3
  • 10

2 Answers2

2

"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 this as the reference to the global context — what code targeted at browsers would call "window":

(function() {
  var global = this; // like "window"

That way, it's possible for the code to "export" symbols:

  global.Foo = someFunction;

Another similar trick is to do this:

(function(global) {
  // ...
})(this);

That has pretty much the same effect.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    Err..the OP is already instantiating a var in the global scope (by referencing 'this') at line 8 of the example: 'Backbone = this.Backbone = {};' – Rob Raisch May 20 '11 at 15:38
  • @Rob Raisch ah yes - well in any case it wasn't done as explicitly as it's done in the Underscore source, for example. Anyway I mostly just needed to provide an affirmative answer longer and more interesting than simply the word, "Yes." :-) – Pointy May 20 '11 at 15:44
0

With ECMAScript 5 strict mode (and thus future versions of JavaScript), only Pointy’s version will work, because "this" does not point to the global object in non-method functions, any more. Instead:

(function() {
    "use strict";
    console.log("This is "+this); // "This is undefined"
}());
Axel Rauschmayer
  • 25,381
  • 5
  • 24
  • 17