此代码来自jquery.validate.js。我认为这是一个自动执行的函数,但我很难解析第二个函数声明的语法。函数($){}是第一个函数的参数,即工厂吗?
(function (factory) {
alert("In jquery.validate.js factory");
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else {
factory( jQuery );
}
}(function ($) {
... //body of function
});
答案 0 :(得分:1)
这是我们今天看到的常见库模式,起初它让我感到奇怪。花了一段时间才明白发生了什么。
首先,这是一个传入函数的自执行函数。在我们查看操作之前,先看一下构造。
// 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 $.
});