In-depth analysis of javascript immediate function execution-javascript tips-js tutorial

Source: Internet
Author: User
In Javascript, any function creates an execution context during execution, because the variables and functions declared for the function may only be within the function, when calling a function, a simple method is provided to create a free variable or a private sub-function. Javascript is more casual than other programming languages, so javascript code is full of various wonderful writing methods, sometimes confused;
Of course, understanding the various types of writing is also a further in-depth understanding of the characteristics of javascript language.

JavaScript function syntax

A function is a block of code enclosed in curly braces. The keyword function is used before:

Function functionname ()
{
Here is the code to be executed
}

When this function is called, the code in the function is executed.

A function can be called directly when an event occurs (for example, when a user clicks a button), and JavaScript can call the function anywhere.

Tip: JavaScript is case sensitive. The keyword function must be in lower case and must be in the same case as the function name.

(Function (){...} ) () And (function (){...} () Is a common method of writing two types of javascript Functions for immediate execution;

Initially I thought it was an anonymous function wrapped in parentheses, and then added a bracket to call the function. Finally, the function was defined and executed immediately;
It was later found that this was not the reason for the 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. 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 description of a function differs from that of a function expression:

1. When parsing Javascript code, the javascript engine will "Function declaration upgraded" (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.

Example:

FnName (); function fnName (){...} // normal, because the function declaration is upgraded, the function call can be fnName (); var fnName = function () {...} before the function declaration (){...} // an error is reported. The variable fnName does not save reference to the function. function calling must be performed after the function expression var fnName = function () {alert ("Hello World ");}(); // The function expression is enclosed in parentheses. When the javascript engine parses the function, it immediately calls function fnName () {alert ("Hello World") ;}(); // No error is reported, however, the javascript engine only parses the function declaration and ignores 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 uses the function keyword at the beginning as the function declaration,

Error: A function name is required.

After understanding some basic functions, let's look back at (function (){...} ) () And (function (){...} () These two methods of writing the function immediately,

Initially I thought it was an anonymous function wrapped in parentheses and followed by parentheses to call the function immediately. At that time, I didn't know why to add parentheses;

Later, I realized that the function must be a function expression and cannot be a function declaration if it can be called immediately by adding parentheses behind the function body.

(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 private scopes. If some variables are declared in global or local scopes in projects developed by multiple people, they may be overwritten by others with variables of the same name.

According to the characteristics of javascript function scope chain, this technology can be used to simulate a private scope, using anonymous functions as a "container", "Container" can access external variables internally, 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.

The above content is a small Editor to introduce you to the javascript immediate execution function, I hope you like it.

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.