An in-depth analysis of JavaScript _javascript techniques for immediate execution of functions

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

JavaScript is more casual than other programming languages, so the JavaScript code is full of exotic flowers and sometimes mirrors;
Of course, understanding the various types of writing is also a further in-depth understanding of JavaScript language features.

JavaScript function syntax

A function is a block of code wrapped in curly braces, preceded by a keyword function:

function functionname ()
{
Here is the code to execute
}

When the function is called, the code inside the function is executed.

You can call a function directly when an event occurs (for example, when a user clicks on a button), and it can be invoked anywhere by JavaScript.

Tip: JavaScript is sensitive to case sensitivity. The keyword function must be lowercase and must be called with the same case as the function name.

(function () {...}) () and (function () {...} ()) is a common form of two JavaScript execution functions immediately;

Initially I thought it was a bracket to wrap the anonymous function, and then put parentheses in the back to call the function, and finally achieve the purpose of execution immediately after the function definition;
It was later found that the parentheses were not the case. 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.

function 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:

One, the JavaScript engine will be "function declaration elevation" (function declaration hoisting) to declare functions on the current execution environment (scope) when parsing JavaScript code. The function expression must wait until the JAVASCIRTP engine executes its line to parse the function expression from the top and the next line.

Second, the function expression can be immediately called with parentheses to call the function, the function declaration can not be called only in the form of FnName ().

Example:

 FnName (); 
 function FnName () { 
  ... 
 } 
 Normal, because the function declaration is "promoted", the function call can be 
 fnname () before the function declaration; 
 var fnname = function () { 
  ... 
 }//error, variable fnname has not yet saved a reference to a function that must be
 var fnname = functions () {alert after a function expression 
  ("Hello World"); 
 } (); 
 The function expression is followed by parentheses, and the function functions 
 fnname () { 
  alert ("Hello World") is immediately invoked when the JavaScript engine resolves here; 
 (); 
 There is no error, but the JavaScript engine resolves the function declaration only, ignoring the parentheses behind it, and the function declaration will not be invoked 
 () { 
  console.log ("Hello World"); 
 } ();
 Syntax error, although the anonymous function is part of a function expression, but no assignment is performed, 
//So the JavaScript engine treats the beginning function keyword as a functional declaration.

Error: Requires a function name

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 did not know why to add parentheses;

It became clear that the function must be a function expression, not a function declaration, to be called immediately after the function body was appended with parentheses.

 (function (a) { 
  console.log (a);//firebug output 123, using () operator 
 }) (123); 
 (function (a) { 
  console.log (a);//firebug output 1234, use () 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 = 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?

JavaScript does not use the concept of a private scope, if a number of people on the development of the project, in the global or local scope of the declaration of some variables, may be inadvertently other people with the same name to overwrite the variable.

Depending on the nature of the 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.

The above content is small series to introduce the JavaScript immediately executive function, I hope you like.

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.