Reputation: 4796
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 = {};
}
Upvotes: 1
Views: 226
Reputation: 6836
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.
Upvotes: 3