javascript - 有人可以告诉我这个 javascript 代码在做什么吗

标签 javascript jquery

此代码来自 jquery.validate.js。我认为这是一个自执行函数,但我很难解析关于第二个函数声明的语法。 function($) {} 是第一个函数的参数,即工厂?

(function (factory) {
    alert("In jquery.validate.js factory");
    if ( typeof define === "function" && define.amd ) {
        define( ["jquery"], factory );
    } else {
        factory( jQuery );
    }
}(function ($) {
... //body of function
});

最佳答案

这是我们今天看到的一种常见的库模式,起初我觉得很奇怪。花了一段时间才明白发生了什么。

首先,这是一个传入函数的自执行函数。在查看操作之前,让我们先查看构造。

// Self executing function that takes no arguments.
(function () { 
    // Some code here.
})();



// Self executing function that takes an argument.
(function (argument) {
     alert(argument);
})("Hello World");



// Self executing function that takes function as argument.
(function (factory) {
   // Self executing. Executes as soon as the script is loaded.
   // At this point, factory = the function below.
})(function (param) {
   // Not self executing! Must be called.
});

现在我们了解了这里发生的事情的构造,让我们看一下这段代码:

// If there is a variable called "define", and that variable is a function, call that function with the paramenter jQuery and pass it the function. This is how we define a library in RequireJS.
if ( typeof define === "function" && define.amd ) {
    define( ["jquery"], factory );
} else {
    // This is how we define the jQuery library everywhere else in the world. We pass the global window.jQuery into the function.
    factory( jQuery );
}

现在大家在一起了,

// Define jQuery.
(function (factory) {
    // If using RequireJS, define jQuery by calling the define function with the jQuery factory.
    if ( typeof define === "function" && define.amd ) {
         define( ["jquery"], factory );
    } else {
        // Otherwise, just call the jQuery factory.
        factory( jQuery );
    }
}(function ($) {
    // Use JQuery or $.
});

关于javascript - 有人可以告诉我这个 javascript 代码在做什么吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49651384/

相关文章:

javascript - 在根级别显示加载指示器,直到所有路由解析完成

javascript - 引用错误 : json is not defined when AJAX call the server method

javascript - Hitboxes 创建策略和等距移相器实现

javascript - "TypeError: undefined is not a function"

JQuery Datepicker 上一个和下一个图标未显示在 JQuery Tabs 元素中?

javascript - 水平居中显示 : table-row 的 div 内容

javascript - 如何将 Firebase 与 Wix 连接

events - 设置事件后运行事件函数

javascript - 当两个可能的 .data 属性之一具有所需值时,在 jQuery 中选择元素

javascript - FullPage.js 在桌面上的淡入淡出效果,禁用并在较小的设备上获得默认滚动