This question already has an answer here:
Ok so I'm writing myself a js library for a project and I have a question. Like most other libraries out there, to preserve my variable scope I am wrapping my code in this:
(function() {
// my code here
})();
Now my question is this: I notice jQuery passes in the window object and sets its own document object like this:
(function(window) {
var document = window.document;
})(window);
Does anyone know why they do this?
Yes! Since the window in this function is a local variable now it allows minify its name. Also access to the local variables should be faster than to the global ones.
You can access faster to local vars, also you can shorten the variable name "window" (and even "document") with something like: