Js (function (){...}) () Execute the function writing comprehension now, js

Source: Internet
Author: User

Js (function (){...}) () Execute the function writing comprehension now, js
Javascript is more casual than other programming languages, so javascript code is full of various wonderful writing methods. Sometimes it is difficult to understand. Of course, Understanding various types of writing is also a further in-depth understanding of the features of javascript language.

(Function (){...} ) () And (function (){...} () Is a common method of writing two types of javascript Functions to execute functions immediately. At first I thought it was an anonymous function wrapped in brackets, And then I added a bracket to call the function, finally, the purpose of immediate execution after function definition was achieved. Later, we found that this was not the reason for parentheses. To understand how to execute a function immediately, you must first understand some basic concepts of the function.

Function declaration, function expression, anonymous Function

Function declaration: function fnName (){...}; Declare a function using the function keyword, and then specify a function name, called the function declaration.

Function expression var fnName = function (){...}; Declare a function using the function keyword, but do not name the function. Finally, assign an anonymous function to a variable called a function expression, which is the most common syntax form of a function expression.

Anonymous function: function () {}; declares a function using the function keyword, but does not name the function, so it is called an anonymous function,An anonymous function is a function expression.Anonymous functions have many functions. If a variable is assigned, a function is created. If an event is assigned, it is an event handler or a closure.

The difference between the Function declaration and the Function expression is that, 1. When parsing Javascript code, the javascript engine will 'function declaration elevated '(Function declaration Hoisting) The Function declaration in the current execution environment (scope, the function expression will parse the function expression from the top row to the next row only when the cirtp engine executes it to the row where it is located. 2. The function expression can be immediately called with parentheses after it, function declaration is not allowed. It can only be called in the form of fnName. The following are two examples of differences between the two.

FnName (); function fnName (){...} // normal, because the 'upgrade' function declaration can be called before the function declaration fnName (); var fnName = function (){...} // an error is reported. The fnName variable does not save reference to the function. Function calling must be performed after the function expression.

 

Var fnName = function () {alert ('Hello World') ;}(); // brackets are added after the function expression, when the javascript engine resolves this field, it can immediately call the function fnName () {alert ('Hello World') ;}(); // No error will be reported, but the javascript engine only parses the function declaration, ignore the parentheses. The function declaration will not be called function () {console. log ('Hello World') ;}(); // syntax error. Although an anonymous function belongs to a function expression, no value assignment is performed, // Therefore, the javascript engine regards the function keyword at the beginning as a function declaration, and an error is returned: A function name is required.


After understanding some basic functions, let's look back at (function (){...} ) () And (function (){...} () I thought it was an anonymous function wrapped in brackets and followed by a bracket to call the function immediately. I didn't know why to add parentheses, later, I realized that the function can be called immediately by adding parentheses behind the function body.Must be a function expression, not a function declaration.

 

(Function (a) {console. log (a); // firebug outputs 123, using the () operator}) (123); (function (a) {console. log (a); // firebug outputs 1234, using the () operator} (1234 ));! Function (a) {console. log (a); // firebug output 12345, use! Operator }( 12345); + function (a) {console. log (a); // firebug outputs 123456, using the + operator} (123456);-function (a) {console. log (a); // firebug outputs 1234567, using the-operator} (1234567); var fn = function (a) {console. log (a); // firebug output 12345678, using the = Operator} (12345678)

You can see the output result and add it before the function! , +,-, And even comma (,) can all be executed immediately after function definition, and (),! , +,-, =, And other operators,Convert the function declaration to a function expression.It eliminates the ambiguity between the javascript engine's identification of function expressions and function declarations, and tells the javascript engine that this is a function expression. Instead of a function declaration, you can add parentheses and immediately execute the function code.

Brackets are the safest method, because! , +,-, And other operators can also perform operations with the return value of the function, sometimes causing unnecessary trouble.

But what is the purpose of this writing?

Javascript does not use the concept of private scopes. If you declare some variables in global or local scopes on projects developed by multiple people, it may be overwritten by others with variables of the same name. According to the features of javascript function scope chain, this technology can be used to simulate a private scope, using an anonymous function as a "container", the "Container" can access external variables, while the external environment cannot access the internal variables of the "container", so (function (){...} ) () Internal Defined variables do not conflict with external variables, commonly known as "anonymous package" or "namespace ".

JQuery uses this method to wrap JQuery code in (function (window, undefined ){... Jquery code ...} (Window), when calling JQuery code in the global scope, it can protect JQuery internal variables.

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.