Writing Explanation of Formal and Real Parameters of Anonymous Function when jquery Encapsulates Plug in

  • 2021-07-21 06:50:11
  • OfStack

We often see the following code in jquery plug-in


;(function ( $, window, document, undefined ){
// Specific code in function body 
})(jQuery, window,document);

1. The semicolon at the front of the code can prevent multiple files from being compressed and merged into other files without a semicolon in the last line of statements, which causes syntax errors after merging.

2. The anonymous function (function () {}) (); Since Javascript executes expressions from inside to outside of parentheses, you can use parentheses to enforce declared functions. Avoid conflict between variables inside and outside the function.

3. $argument: $is the abbreviation of jquery, and many methods and class libraries also use $. Here, $accepts jQuery objects, which is also to avoid $variable conflicts and ensure that plug-ins can run normally.

4. window and document arguments accept window and document objects respectively, and window and document objects are all in the global environment, while window and document in the function body are actually local variables, not global window and document objects. This has the advantage of improving performance and reducing the query time of scope chain. If you need to call window or document objects many times in the function body, it is very necessary to pass window or document objects as parameters. Of course, if your plug-in doesn't use these two objects, then you don't have to pass these two parameters.

5. Finally, there is one undefined parameter left, so what is this parameter used for? It seems a bit redundant. undefined is not supported in the browsers of the older generation, and errors will be reported if used directly. Compatibility should be considered in js framework, so one formal parameter undefined is added


Related articles: