What is “define” in RequireJS?

2019-06-14 16:10发布

问题:

What is define in RequireJS? Is it a constructor or a function or...?

  1. Create module app. Before create module it loads module app2. After initialize callback:

    define(
        'app',
        ['app2'],
        function( app2 ){
            console.log(app2)
        }
    ); 
    
  2. What's this syntax?

    define(function (require) {
        var logger = require("./app2");
        console.log(logger);
    });
    
  3. And this:

    define({
        color: "black",
        size : "large"
    });
    

回答1:

From the comments:

 The function that handles definitions of modules. Differs from
 require() in that a string for the module should be the first argument,
 and the function to execute after dependencies are loaded should
 return a value to define the module corresponding to the first argument's
 name.

And its signature is:

define = function (name, deps, callback)

In javascript every function is a Function object, so in both cases you are passing to define an object.

//Allow for anonymous modules
if (typeof name !== 'string') {
    //Adjust args appropriately
    callback = deps;
    deps = name;
    name = null;
}