Understanding of JavaScript self-running functions (function () {}) ()

Source: Internet
Author: User

Open the jquery source file today (jquery-1.8.3) and see how the jquery initialization process is

( function ( window, undefined ) {      // .... })( window );

Beginning to understand this writing, after a few searches finally understand its usage and why it is used, we step by step to analyze.

1, first we simplify the wording

After removing the parameters, the simplified wording can be written

( function (){      console.log( "Hello World" ); })();

This is used later as an example.

2, function declaration and function expression

There are many articles on the web that introduce the creation of JavaScript functions, which tell us that there are two ways to create JavaScript functions: function declaration and function expression.

//function definition (also called function declaration) function func1() {      console.log( "Hello World1" ); } func1(); // function expression var func2 =  function (){      console.log( "Hello World2" ); }; func2();

The first method of " function definition " is the standard method of function definition, and the call to function func1 can appear before the function definition;

The second is called the "function expression", and unlike the function definition, the call to the function Func2 must appear after the variable FUNC2, because the variable FUNC2 is essentially a variable that points to a function object, which is essentially the same as the way we define the ordinary variable; Another point is that the function name created by the function expression can not be written, we call it an anonymous function. For example,

var a = 10;var F = function () {//code ...};
f (); Call function f

Here we point the variable f to the anonymous function created on the right side of the assignment operator, and then we can call the anonymous function directly through F (), so the question is, can we just call it immediately after creating the anonymous function and not go to the superfluous assignment to the variable F?

Let's try.

function () {Console.log ("Hello World3");} ();//Output:uncaught syntaxerror:unexpected token (

Sorry for the error, why is this? Then we look back at the syntax difference between the function definition and the function expression.

Functions definition: Function FuncName () {//code ...} funcName ();

Functions expression: function [FuncName] () {//code ...} funcName ();

The syntax difference between the two is very small, so when the JavaScript interpreter interprets that the function keyword is to consider this code as a functional definition or function expression? According to JavaScript syntax, statements that begin with a function are defined as functions, and function definitions must have a function name, and functions are executed through the function name, but it is obvious that the function () {};() does not conform to the syntax specification, which explains why an error has been made. Therefore, any method that allows the JavaScript interpreter to interpret this statement as a function expression should allow this code to execute successfully. So here's the question: How do you do that?

var a = 1;

This is a simple expression, so we think we can put an appropriate operator in front of this statement, where there can be only one function object operand (JavaScript statement) to the right of the operator, so we should use the operand (unary) operator for the object , let's try the various operators.

! function () {Console.log ("Hello World2");} ();          Hello world2+ function () {console.log ("Hello World3");} ();        Hello World3-function () {console.log ("Hello World4");} ();        Hello World4delete function () {console.log ("Hello World5");} ();    Hello world5void function () {console.log ("Hello World6");} ();    Hello World6

These operators can achieve our goal of having the JavaScript interpreter create this function in a way that creates a function expression. It's up to you to decide which operator to use, but it's clear that we want to use the most concise way.  In practice, some Daniel tend to use "!", which has a lot of discussion in StackOverflow. Http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function

3, round brackets parenthesis

Another more commonly used notation, the use of jquery, is to use parentheses as a grouping operator to make the execution function statement mandatory to create this anonymous function in the form of a function expression.

The inner code of the first notation () grouping operator can only be an expression, where an anonymous function (function () {/* Code ... */};) () is created and returned as a functional expression ();//The second method creates and runs the anonymous function directly inside the top-most bracket as an expression ( function () {...} (););

(function () {Console.log ("Hello World6");}) ();    Hello World6
(function () {Console.log ("Hello World6");} ());    Hello World6


4, conclusion

Analysis, in fact, the purpose of this writing is simple: To define an anonymous function and execute. As for why this is written, this is the use of the properties of the closure closure to initialize global variables and to control the scope of these global variables inside the anonymous function. As for the closures, next time, let's go off.

Resources

1, Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

2, http://www.zhihu.com/question/20292224

3, http://www.zhcexo.com/round-brackets-in-javascript/

4, http://swordair.com/function-and-exclamation-mark/

Understanding of JavaScript self-running functions (function () {}) ()

Related Article

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.