There's not much point to #1. window
is read-only and cannot be redefined, so there's no need to capture its value at a point in time the way #1 does. #2 is fine.
The pattern #1 uses is primarily useful for capturing things that may get changed by other code later, e.g.:
var x = 1;
(function(x) {
setTimeout(function() {
console.log("inside, x = " + x);
}, 100);
})(x);
x = 2;
console.log("outside, x = " + x);
...or to get convenient shorthand names for things:
(function(d) {
var div = d.createElement("div");
div.innerHTML = "Hi";
d.body.appendChild(div);
})(document);
It was also commonly used for getting undefined
in case the undefined
identifer was modified:
(function(u) {
console.log(typeof u); // "undefined"
})(/*Note there's no argument passed*/);
Now that undefined
is read-only and cannot be redefined, there's no real need to do that anymore.