开发者

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

This question already has answers here: What advantages does using (function(window, document, undefined) { ... })(window, document) confer? [duplicate] (4 answers) 开发者_运维问答 Closed 8 years ago.

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:

(function(w, d)(){

    // use w and d var

})(window, document)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜