Understanding of (function (window, undefined) {}) (window) Writing in JS

Source: Internet
Author: User

In jquery, we often see the following section:Code:
; (Function ($, window, document, undefined ){

// Code of the function body

}) (Jquery, window, document );

First, let's talk about the following points that are worth advocating:
1. The semicolon at the beginning of the code can prevent compression and merging of multiple files into the statement of the last line of other files without a semicolon, resulting in a syntax error after merging.
2. Anonymous functions (function () {}) ();: Since the JavaScript Execution expression is from inside the parentheses to the outside, you can use parentheses to forcibly execute declared functions. Avoid internal and external variable conflicts.
3. $ real parameter: $ is short for jquery. Many methods and class libraries use $. Here, $ accepts jquery objects to avoid $ variable conflicts and ensure that the plug-in can run normally.
4. Window and document parameters accept window, Document Object, window, and document object in the global environment respectively. In the window function, document is actually a local variable, it is not a global window, Document Object. This can improve performance and reduce the query time of the scope chain. If you need to call the window or Document Object multiple times in the function body, in this way, it is necessary to pass the window or document object as a parameter. Of course, if your plug-in does not use these two objects, you do not need to pass these two parameters.
5. The last undefined parameter is left. What does this parameter use? It seems redundant. Undefined is not supported in older browsers. An error will be reported if it is used directly. The JS framework must take compatibility into account. Therefore, an undefined parameter is added.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.