3

我发现了这个代码片段,但我不明白 a 和 b 是在哪里给出的。它可以工作,所以它可能是 $window。jquery 在这里做什么?

function (a, b) {
    var c = a('meta[name="csrf-token"]').attr("content");
}(jQuery)

的HTML:

  <meta content="authenticity_token" name="csrf-param" />
<meta content="/Zsc0Ma07P8gupCp2k3Iu77nTOQDStpt6bToOlVt/gc=" name="csrf-token" />
4

2 回答 2

4

它只是定义ajQuery函数内部的别名,以及b的别名undefined

也许你会发现这更熟悉:

function ($, b) {
    var c = $('meta[name="csrf-token"]').attr("content");
}(jQuery)

使用别名undefined通常是为了获得更短的代码,以最小化带宽。

于 2013-05-13T10:40:00.583 回答
4
function (a, b) {
    var c = a('meta[name="csrf-token"]').attr("content");
}(jQuery)// the function call is made here

提供的第一个参数是jQuery,大jQuery对象,相当于$. 在您的通话中,a = jQuery默认b = undefined情况下,从未提供过。

(function(a, b) {
    console.log(a); // 5
    console.log(b); // 3
})(5, 3);

正如@dystroy 指出的那样,这是一个较短的代码技巧,但它通常不用于缩短undefined,可以通过任何参数遗漏轻松获得。JavaScript 通常会被缩小,但缩小器无法缩小默认关键字,例如documentor window。通过减小文件大小来提高性能。

一个更常见的场景是:

!function(w, d){
    w.onload = function() {
        var x = d.getElementById("whatever");
    };
}(window, document);

以上所有内容都应该是 IIFE,或立即调用。使用括号或任何数学运算符将求值强制为表达式。

更新

将参数传递给函数。

(function(a, b) { // here I am defining an anonymous function. It has no name
    console.log(a); // It takes two params, a and b.
    console.log(b);
})(5, 3); // Because of the () parentheses around it: (function(){})
// the function is evaluated as an expression. 
// because of the second group of params (5, 3) the function is called.

想象一下你正在这样做。

function do(a, b) {
    // bla bla
};
do(5, 3);

将函数定义和函数调用粘合在一起,您将得到:

(function(a, b) {})(5, 3);
于 2013-05-13T10:40:47.333 回答