Why does jQuery pass the window object into their

2019-02-06 06:16发布

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?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-06 06:44

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.

查看更多
乱世女痞
3楼-- · 2019-02-06 06:56

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)
查看更多
登录 后发表回答