In following code of jQuery
, why next parameter is undefined
JavaScript:
(function(a,b){
....
})(window)
Here a=window
but b=undefined
, why is so?
In following code of jQuery
, why next parameter is undefined
JavaScript:
(function(a,b){
....
})(window)
Here a=window
but b=undefined
, why is so?
That's a common technique to assure you have a true undefined
value to check against since the undefined
property of the window object used to be writeable and thus could not reliably be used in checks. Since only one parameter is handed over to the function, the second one is assured to be undefined
. The name of that variable does not matter, it could be undefined
but as well foobar
or, as in this case, (because this is the shortest possible way saving valuable bytes) b
.
Now you can safely check for undefinedness of variables, because you are sure about the value of b:
// overwriting the global undefined property works in old browsers
undefined = 3;
(function(a,b){
var asd; // not initialised, thus undefined
if (asd === undefined){
// should trigger, but won't because undefined has been overwritten to 3
}
if (asd === b){
// is safe, bcause you know that b is undefined
}
})(window)
New browsers (IE9, FF4+, Chrome) obey the EcmaScript5 specification and undefined
is not writable any more.
Because you are not passing anything for the second parameter. You are passing just one, namely window
.
Your code
(function(a,b){
....
})(window)
defines a function and calls it immediately. The last line above actually calls the function using the window
parameter. If you pass 2 parameters there, b
will not be undefined.
This is immediate javascript function syntax you're trying to use:
(/* function body */)(/* params */)
Named function defined like:
function addNumbers(a, b){
alert(a + b);
}
You call it:
addNumbers(1, 2)
Or similar immediate function (defined and executed at the same time):
(function(a, b){
alert(a + b);
})(1, 2)