With my limited understanding of RequireJS and Node.js (plus JavaScript in general), I usually take a look at the source of some well-known JavaScript libraries. Every time I see something like this:
( // Wrapping
function (root, factory) {
if (typeof exports === 'object') { // Node.js
var underscore = require('underscore');
var backbone = require('backbone');
module.exports = factory(underscore, backbone);
} else if (typeof define === 'function' && define.amd) { // Require.JS
define(['underscore', 'backbone'], factory);
}
}(this, function (_, Backbone) { // Factory function, the implementation
"option strict";
function Foo() {}
return Foo; // Export the constructor
})
); // Wrapping
What I can understand (hopefully):
- The anonymous function that wraps the code is automatically executed when the script is uncluded in a
<script>
tag - This code works with both RequireJS and Node.js (
if
checks in the very beginning); the result offactory
function is either assigned tomodule.exports
(Node.js) or used as argument ofdefine
function (RequireJS).
Q1: how this code works without RequireJS and Node.js? if
and else if
checks would fail, factory
function is never executed and the scripts returns nothig.
Q2: what's the purpose of passing this
as root
argument? It's never used