user656925
user656925

Reputation:

How is `exports` used to initialize Backbone?

  // Save a reference to the global object (`window` in the browser, `exports`
  // on the server).
  var root = this;

What is exports? I can understand setting root.Backbone to an object literal as now one can add properties to it.

However, the comment in the source above implies that this points to window in browsers and exports on the server?

Is this true?

The reason I ask is because this code here:

  var Backbone;
  if (typeof exports !== 'undefined') {
    Backbone = exports;
  } else {
    Backbone = root.Backbone = {};
  }

Why would you define all the modules outside of the namespace (to exports), defeating the purpose of of the closure the library is contained it.

Upvotes: 0

Views: 1234

Answers (1)

jevakallio
jevakallio

Reputation: 35950

exports is the name of the exported object in the CommonJS module format, primarily used by node.js.

In CommonJS every javascript source file is a module, and whatever you assign to exports will be the "return value" of that file. So the line in Backbone source code:

Backbone = exports;

Says: "define Backbone as the export object of this module." Later on, when they attach properties such as Backbone.Model to the Backbone root object, they are attached to the export value.

Upvotes: 2

Related Questions