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 = {};
}
exportsis a CommonJS-pattern global (think require.js and node.js) that is used to provide code modularly. The top check is seeing ifexportsis 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:
exportsitself 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:The
Backboneglobal gets access to all of this tertiary depth necessary for the modular pattern. Otherwise,Backbonewould simply start with a boring old emptyobjectdefinition.