I found this codesnipe and I do not understand where the a and b is given. It works, so it may be $window. What is jquery here doing?
function (a, b) {
var c = a('meta[name="csrf-token"]').attr("content");
}(jQuery)
the html:
<meta content="authenticity_token" name="csrf-param" />
<meta content="/Zsc0Ma07P8gupCp2k3Iu77nTOQDStpt6bToOlVt/gc=" name="csrf-token" />
function (a, b) {
var c = a('meta[name="csrf-token"]').attr("content");
}(jQuery)// the function call is made here
The first argument provided is jQuery, the big jQuery object, equivalent to the $. In your call, a = jQuery and b = undefined by default, as it was never provided.
(function(a, b) {
console.log(a); // 5
console.log(b); // 3
})(5, 3);
As @dystroy points out, this is a shorter code trick, but it's generally not used to shorten undefined, which can easily be obtained through any param omission. JavaScript is often minified, but minifiers cannot minify default keywords such as document or window. Performance is increased by diminishing the file size.
A far more common scenario is:
!function(w, d){
w.onload = function() {
var x = d.getElementById("whatever");
};
}(window, document);
All the above should be IIFEs, or Immediately invoked. Use parentheses or any mathematical operator to force evaluation as an expression.
Update
Passing parameters to a function.
(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.
Imagine you are doing this.
function do(a, b) {
// bla bla
};
do(5, 3);
Glue together the function definition and the function call and you get:
(function(a, b) {})(5, 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With