1

I'm trying to read the source code of Backbone.js. I am quite perplexed by the following code, which is supposed to declare the top-level namespace of Backbone. Anyone can help give some clue or explanations? Some useful links to enlighten this is also very welcome!

// 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 = root.Backbone = {};
  }

1 Answer 1

3

exports is a CommonJS-pattern global (think require.js and node.js) that is used to provide code modularly. The top check is seeing if exports is available. If it is, the Backbone global is given the exports reference so it can be properly exported modularly.

If you are not loading Backbone through an AMD-style loader, it is defined by a standard object literal.

Further reading on the matter:

http://dailyjs.com/2010/10/18/modules/

What is the purpose of Node.js module.exports and how do you use it?

What is exports and prototype in Javascript?

Further exposition:

exports itself carries some added "beefiness" beyond a normal object literal. This "beefiness" is required for the CommonJS modular pattern. Note here in the Node.js source:

function Module(id, parent) {
  this.id = id;
  this.exports = {};
  this.parent = parent;
  if (parent && parent.children) {
    parent.children.push(this);
  }

  this.filename = null;
  this.loaded = false;
  this.children = [];
}

module.exports = Module;

The Backbone global gets access to all of this tertiary depth necessary for the modular pattern. Otherwise, Backbone would simply start with a boring old empty object definition.

1
  • Thank you for your detailed answer. But I am not very clear about the meaning of "the Backbone global is given the exports reference so it can be properly exported modularly." Why use "Backbone = exports;" instead of "exports = root.Backbone" ?
    – lkahtz
    Jan 3, 2013 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.