开发者

pattern for module targeting browser and nodejs

backbone and underscore are usable in both the browser and nod开发者_如何转开发ejs.

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 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.


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"
}());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜