Why does this JavaScript code (module template for RequireJS and Node.js) work?

With my limited understanding of RequireJS and Node.js (plus JavaScript in general), I usually 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):

  • An anonymous function that wraps the code is automatically executed when the script is not included in the tag <script>
  • This code works with RequireJS and Node.js requirements ( ifat the very beginning); the result of the function is factoryeither assigned module.exports(Node.js) or used as an argument to the function define(RequireJS).

Q1: RequireJS Node.js? if else if , factory nothig.

Q2: this root?

+5
2

, , , , . , , UMD - Universal Module Definition. , https://github.com/umdjs/umd

:

Q1 RequireJS AMD - - NodeJS , AMD factory .

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);
} else {
    // Browser globals
    factory(root._, root.Backbone);
}

, , -, nekman , window , , , factory, script . , .

+5

Q1: if else if , , underscore Backbone <script>. Backbone.localStorage, .

Q2: this " " (window global Node.js). . factory .

+2

All Articles