Deep understanding of immediate execution functions (function () {...}) in JavaScript () _ Basic knowledge

Source: Internet
Author: User
Tags function definition types of functions

JavaScript is quite casual compared to other programming languages, so the JavaScript code is full of all kinds of exotic work, and sometimes, of course, understanding the various types of writing is a further insight into JavaScript language features.

(function () {...}) () and (function () {...} ()) is a common way for two kinds of JavaScript to execute functions immediately, initially I thought it was a bracket wrapped anonymous function, followed by parentheses to call the function, finally reached the function definition immediately after the purpose of execution, and later found that the reason for parentheses is not so. To understand the immediate execution function, you need to first understand the basic concepts of some functions.

function declarations, function expressions, anonymous functions

function declaration: Functions fnname () {...}; Use the function keyword to declare a function, and then specify a function name, called a function declaration.

Functional expression var fnname = function () {...}; Using the function keyword to declare a function, but not naming the function, and finally assigning an anonymous function to a variable called a function expression, is the most common form of function expression syntax.

anonymous function: function () {}; Declaring a function with the function keyword, but not naming it, is called an anonymous function, an anonymous function is a function expression, and an anonymous function has many functions, giving a variable to create a function, assigning an event to an event handler or creating a closure, and so on.

The difference between a function declaration and a function expression is that the JavaScript engine, when parsing JavaScript code, will ' function declaration elevation ' (function declaration hoisting) The declaration of functions on the current execution environment (scope). The function expression must wait until the JAVASCIRTP engine executes to its line to parse the function expression from the top and the next line, two, the function expression can be immediately called with parentheses, and the function declaration can not be called only in FnName () Form. Here are two examples of the difference between the two.

Copy Code code as follows:

FnName ();
function FnName () {
...
}
Normal, because the function declaration of ' ascension ' can be called before the function declaration

FnName ();
var fnname=function () {
...
}
Error, variable fnname has not yet saved a reference to the function, the function call must be after the function expression

Copy Code code as follows:

var fnname=function () {
Alert (' Hello world ');
}();
The function expression is followed by parentheses, and the function can be called immediately when the JavaScript engine resolves here
function FnName () {
Alert (' Hello world ');
}();
No error, but the JavaScript engine only resolves function declarations, ignoring the parentheses behind them, and the function declaration is not invoked
function () {
Console.log (' Hello world ');
}();
Syntax error, although the anonymous function belongs to a function expression, but does not have an assignment operation,
So the JavaScript engine declares the function keyword that starts with an error: Requires that a function name be required

After you understand some basic concepts of functions, look back (function () {...}) () and (function () {...} () These two types of functions are immediately executed, initially I thought it was a bracket wrapped anonymous function, and followed by parentheses to call the function immediately, then do not know why the parentheses, then understand that to be called immediately after the function body parentheses, then this function must be a function expression, not a function declaration.

Copy Code code as follows:

(function (a) {
Console.log (a); Firebug output 123, using the () operator
}) (123);

(function (a) {
Console.log (a); Firebug output 1234, using the () operator
} (1234));

!function (a) {
Console.log (a); Firebug output 12345, use! Operator
} (12345);

+function (a) {
Console.log (a); Firebug output 123456, using the + operator
} (123456);

-function (a) {
Console.log (a); Firebug output 1234567, using the-operator
} (1234567);

var fn=function (a) {
Console.log (a); Firebug output 12345678, using the = operator
} (12345678)

You can see the output, in front of the function Plus! , +,-even commas wait until they can be executed immediately after the function definition, and (),! , + 、-、 = operator, all convert function declarations to function expressions, eliminating the ambiguity of JavaScript engine recognition function expressions and function declarations, telling the JavaScript engine that this is a function expression, not a function declaration, can be followed by parentheses, and executes the function's code immediately.

Braces are the safest way to do it because! , +,-and so on, can also be calculated with the return value of the function, sometimes causing unnecessary trouble.

But what is the use of this writing?

The notion of a private scope in JavaScript, if you declare variables in a global or local scope on a project that has been developed by many people, may be accidentally overwritten by someone else with the same name, depending on the characteristics of a JavaScript function's scope chain, You can use this technique to mimic a private scope, with anonymous functions as a "container" where external variables can be accessed within the container, and the external environment cannot access variables inside the container, so (function () {...}) () internally defined variables do not conflict with external variables, commonly known as "anonymous wrapper" or "namespace".

This is what jquery uses to wrap jquery code in (function (window,undefined) {... jquery code ...} (window), you can protect jquery internal variables by calling jquery code in a global scope.

This article is a personal understanding of the collation, if there are errors are welcome to point out that the point of view in this article:

JavaScript Authority Guide, JavaScript advanced programming

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.