此代码来自 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/