Deep understanding (function () {...}) (); and deep understanding of function

Source: Internet
Author: User

Deep understanding (function () {...}) (); and deep understanding of function

1. It is called an anonymous function that runs immediately (also called an immediate function)

2. When an anonymous function is enclosed and a bracket is added to it, this anonymous function can run immediately! It's amazing ~

3. To use a function, we must first declare its existence. The most common method is to use a function statement to define a function.

4. Function object

Function objects are inherent objects in JavaScript. All functions are actually Function objects.

Let's take a look at whether the Function object can directly use the constructor to create a new Function? The answer is yes.

var abc = new Function("x","y","return x*y;"); alert(abc(2,3)); // "6" 

5. If an anonymous function has no name, how can we call it (O_O )?

Anonymous function call ①

var abc=function(x,y){ return x+y; } alert(abc(2,3)); // "5" 

The above operation is actually equivalent to defining a function in another way. This usage is frequently encountered.

For example, when we set a DOM element event processing function, we usually do not set their names, but assign the corresponding event to reference an anonymous function.

Call of anonymous functions ②

Use () to enclose anonymous functions, and then add a pair of parentheses (including the parameter list ).

alert((new Function("x","y","return x*y;"))(2,3));// "6" 

6. What is the role of parentheses?

Parentheses can combine our expressions into blocks, and each block, that is, each pair of parentheses, has a return value. The returned value is actually the return value of the expression in parentheses.

Therefore, when we enclose anonymous functions with a pair of parentheses, in fact, parentheses return the Function object of an anonymous Function.

Therefore, adding an anonymous function to the parentheses is like a function with a name, and we get its reference position. Therefore, if the parameter list is added after the referenced variable, the call form of the common function is implemented.

7. function declaration, function expression, and 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. Therefore, it is called an anonymous function. An anonymous function belongs to a function expression and has many functions, assign a variable to create a function, assign an event to be an event handler or create a closure, and so on.

The difference between function declaration and 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 Javascirtp engine executes it to the row where it is located.

2. You can call the function immediately after the function expression with parentheses. The function declaration is not allowed and can only be called in the form of fnName.

Chestnut ①

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.

Chestnut ②

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.

To call the function immediately after the function body is enclosed in parentheses, the function must be a function expression, not a function declaration.

Chestnut ③

(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 all convert the function declaration to a function expression, eliminating the ambiguity of the javascript engine in identifying the function expression and function declaration, and telling 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.