Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery pass the window object into their scope [duplicate]

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?

like image 790
Justin Bull Avatar asked Jan 12 '11 04:01

Justin Bull


2 Answers

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.

like image 172
Andrey M. Avatar answered Oct 11 '22 14:10

Andrey M.


You can access faster to local vars, also you can shorten the variable name "window" (and even "document") with something like:

(function(w, d)(){

    // use w and d var

})(window, document)
like image 32
sebarmeli Avatar answered Oct 11 '22 12:10

sebarmeli