Javascript RequireJS库定义说明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8350699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:39:08  来源:igfitidea点击:

Explanation of define of the RequireJS library

javascriptrequirejs

提问by Wolfgang Adamec

I started to read several tutorials about RequireJS. In none of them was the "define" keyword explained satisfactorily for me. Could someone help me with the following :

我开始阅读一些关于 RequireJS 的教程。在它们中没有一个对我来说满意的“定义”关键字解释。有人可以帮我解决以下问题:

define(
  ["Models/Person", "Utils/random", "jquery"], 
  function (Person, randomUtility, $) {..}
)  

What is "define"? Is define a function with an array and an anonymous function inside of it? Or is it something else? Can someone give me more information about this kind of definitions?

什么是“定义”?是否定义了一个包含数组和匿名函数的函数?或者是别的什么?有人能给我更多关于这种定义的信息吗?

Addition: Thank you nnnnnn and pradeek for your answers. Here in Europe it was 2:30 in the night when I was posting the question. Maybe therefore I didn't recognize it was a simple function call.

补充:感谢 nnnnnn 和 pradeek 的回答。在欧洲,当我发布问题时是晚上 2:30。也许因此我没有意识到这是一个简单的函数调用。

回答by Drew

defineis not specific to RequireJS, it is part of the AMD specification. Burke will note that RequireJS doesn't implement exactly how AMD specifies it, since AMD didn't really keep browsers in mind.

define不是 RequireJS 特有的,它是AMD 规范的一部分。Burke 会注意到 RequireJS 并没有完全实现 AMD 指定它的方式,因为 AMD 并没有真正考虑浏览器。

definedoesn't have an anonymous function in it. defineis a method made available to AMD based JavaScript files for loading their data. Libraries like RequireJS make this available to you. The specific implementation probably isn't valuable to you. So I'll go over the one you provided as it's the most common way to declare a module.

define里面没有匿名函数。 define是一种可用于基于 AMD 的 JavaScript 文件加载其数据的方法。像 RequireJS 这样的库让你可以使用它。具体的实现可能对您没有价值。因此,我将介绍您提供的方法,因为它是声明模块的最常用方法。

define([array], object);

define([array], object);

Array is a list of modules that this module depends on. There is a 1 to 1 relationship between modules and files. You can not have multiple modules in a file nor multiple files for one module.

Array 是该模块所依赖的模块列表。模块和文件之间是一对一的关系。一个文件中不能有多个模块,一个模块不能有多个文件。

Object is the module you are defining. This can be anything, a struct, or a function that returns a struct. Read the docs on RequireJSfor more details.

Object 是您正在定义的模块。这可以是任何东西、结构体或返回结构体的函数。阅读RequireJS上的文档以获取更多详细信息。

If object is a function, the arguments passed to the function are the modules listed as dependencies in the first define argument. It is also important to note than when you pass a function as object, it will only run one time. The methods or properties created on this one instantiation can be accessed at any time though, can then be accessed by other modules that list this module as a dependency.

如果 object 是一个函数,则传递给该函数的参数是在第一个定义参数中列为依赖项的模块。同样重要的是要注意,当您将函数作为 传递时object,它只会运行一次。在这个实例化上创建的方法或属性可以随时访问,然后可以被其他将此模块列为依赖项的模块访问。

Good luck, I recommend playing around with this and reading the docs when things don't make sense. RequireJS docs are great as a quick start on how AMD modules work.

祝你好运,当事情没有意义时,我建议玩这个并阅读文档。RequireJS 文档非常适合作为 AMD 模块如何工作的快速入门。

回答by BlueMonkMN

I found definedefined near the bottom of require.js (I too was wondering what kind of a thing this defineword is, and this is the answer Iwas looking for):

我在definerequire.js 的底部附近找到了定义(我也想知道这个define词是什么东西,这就是正在寻找的答案):

/**
 * 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.
 */
define = function (name, deps, callback) {
    var node, context;

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

    //This module may not have dependencies
    if (!isArray(deps)) {
        callback = deps;
        deps = null;
    }

    //If no name, and callback is a function, then figure out if it a
    //CommonJS thing with dependencies.
    if (!deps && isFunction(callback)) {
        deps = [];
        //Remove comments from the callback string,
        //look for require calls, and pull them into the dependencies,
        //but only if there are function args.
        if (callback.length) {
            callback
                .toString()
                .replace(commentRegExp, '')
                .replace(cjsRequireRegExp, function (match, dep) {
                    deps.push(dep);
                });

            //May be a CommonJS thing even without require calls, but still
            //could use exports, and module. Avoid doing exports and module
            //work though if it just needs require.
            //REQUIRES the function to expect the CommonJS variables in the
            //order listed below.
            deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
        }
    }

    //If in IE 6-8 and hit an anonymous define() call, do the interactive
    //work.
    if (useInteractive) {
        node = currentlyAddingScript || getInteractiveScript();
        if (node) {
            if (!name) {
                name = node.getAttribute('data-requiremodule');
            }
            context = contexts[node.getAttribute('data-requirecontext')];
        }
    }

    //Always save off evaluating the def call until the script onload handler.
    //This allows multiple modules to be in a file without prematurely
    //tracing dependencies, and allows for anonymous module support,
    //where the module name is not known until the script onload event
    //occurs. If no context, use the global queue, and get it processed
    //in the onscript load callback.
    (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};

回答by vine'th

I found this page Why AMD?very helpful. To summarize from this page, AMD specification is helpful in overcoming "write a bunch of script tags with implicit dependencies that you have to manually order" problem. It is helpful in loading the dependencies before executing the required functions, similar to importin other programming languages like python. AMD also prevents the global namespace pollution problem. Check "It is an improvement over the web's current "globals and script tags" because"section.

我找到了这个页面为什么是 AMD?很有帮助。从这个页面总结一下,AMD 规范有助于克服“编写一堆具有隐式依赖项的脚本标签,您必须手动订购”问题。它有助于在执行所需函数之前加载依赖项,类似于importPython 等其他编程语言。AMD 还可以防止全局命名空间污染问题。检查"It is an improvement over the web's current "globals and script tags" because"部分。

回答by undefined behaviour

I think the RequireJs API specificationsums it up pretty well:

我认为RequireJs API 规范总结得很好:

If the module has dependencies, the first argument should be an array of dependency names, and the second argument should be a definition function. The function will be called to define the module once all dependencies have loaded. The function should return an object that defines the module.

如果模块有依赖,第一个参数应该是一个依赖名称数组,第二个参数应该是一个定义函数。一旦加载了所有依赖项,将调用该函数来定义模块。该函数应该返回一个定义模块的对象。

They list examples of all the various syntactic forms of defines.

它们列出了定义的所有各种句法形式的示例。