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
,它可以很容易地通过任何PARAM遗漏而获得。 JavaScript通常会缩小,但缩小器无法缩小默认关键字,如document
或window
。通过减小文件大小来提高性能。
一个更常见的情况是:
!function(w, d){
w.onload = function() {
var x = d.getElementById("whatever");
};
}(window, document);
上述所有应IIFEs,或立即调用。使用圆括号或任何数学运算符来强制评估作为表达式。
更新
将参数传递给函数。
(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);
目前'B'是 – undefined 2013-05-13 10:39:27