JS Execute function immediately

Source: Internet
Author: User

Some summaries after online review, not original

In general, we need to invoke a JavaScript function, the basic condition is defined first, and then called.

If you do not need to display the calling function, so that the function is executed at the time of definition, it can be used to execute the function immediately.

Common notation for executing functions immediately:

1. (function() {...}) () 2. (function() {...} ())

To understand the immediate execution of a function, you need to first understand some basic concepts of functions.

function declarations, function expressions, anonymous functions.

The following is a brief review:

function declaration:

function function_name (ARGS1, arg2, Arg3) {    //  function Body}

You declare a function using the function keyword, and then you specify a function name ( in the function declaration, you must give the function a name ) , which is called a declaration of functions.

function expression:

function [Function_name] (ARGS1, arg2, Arg3) {    //  function Body}

[Function_name] here means that function_name can be ignored.

Or a grammatical form like this:

var function () {...};

The difference between a function expression and a function declaration:

If you do not declare a function name, it must be an expression, but if you declare a function name, how do you determine whether it is a function declaration or a function expression?

ECMAScript is distinguished by context, if function foo () {} is part of an assignment expression, it is a function expression, if function foo () {} is contained within a function body, or at the top of the program, Then it is a function declaration.

Take a look at some examples:

function // function declaration, because it is part of the program var function // function expression because it is part of an assignment expression New function // function expression, because it is a new expression (function() {    function//  functions declaration, because it is part of the function Body });

In the immediate execution function:

(function  foo () {    //  foo Body}) ();

This function is composed of two () , the first one () in fact a function, then here foo is the function declaration or function expression?

The foo function here is the function expression . Although this function has a name foo , it is a function expression.

Why is it?

Because this foo function is () wrapped, and this () in JavaScript is actually an operator, called the grouping operator , and this grouping operator can only contain an expression inside.

Try {    (var//  error, because the grouping operator can only contain an expression and cannot contain a statement, where Var is the statement catch(err) {     // SyntaxError}

Anonymous functions:

function () {};

Declaring a function with the function keyword, but not naming it, is called an anonymous function.

Business:

The difference between a function declaration and a function expression is that:

1. The JavaScript engine will ' function declaration promotion '(function declaration hoisting) Functions declaration on the current execution environment (scope) when parsing JavaScript code, The function expression must wait until the JAVASCIRTP engine executes to its row before the function expression 2 is parsed from the top and the next line, and the function expression can be called immediately after it is appended with parentheses, and the function declaration cannot

Example:

fnname ();functionfnname () {...}//Normal, because the function declaration is ' promoted ', the function call can precede the function declarationfnname ();varFnname=function(){  ...}//error, variable fnname has not saved a reference to the function, the function call must be after the function expressionvarFnname=function() {alert (' Hello World ');} ();//The function expression is appended with parentheses, and the function is called immediately when the JavaScript engine resolves herefunctionFnName () {alert (' Hello World ');} ();//no error is made, but the JavaScript engine only resolves function declarations, ignores the following parentheses, and the function declaration is not calledfunction() {Console.log (' Hello World '); }();//syntax error, although the anonymous function is a function expression, but the assignment operation is not performed,//so the JavaScript engine takes the function keyword at the beginning as a functional declaration, an error: Requires a name

After understanding some basic concepts of function, look back (function () {...}) () and (function () {...} ()) These two methods of executing functions immediately,

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

(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-operator} (1234567); varfn=function(a) {Console.log (a); //firebug output 12345678, using the = operator} (12345678)

You can see the output and add it in front of the function! , +,-even a comma wait for the effect to be executed immediately after the function definition, and (),! , + 、-、 =, and so on, all function declarations are converted into function expressions , eliminating the ambiguity of the JavaScript engine recognition function expressions and function declarations, telling the JavaScript engine that this is a function expression, not a function declaration, you can add parentheses later, And immediately executes the code for the function.

Parentheses are the safest thing to do, because! , +,-et operators also operate on the return values of functions, sometimes causing unnecessary hassles.

The use of this notation:

The concept of a private scope in JavaScript, if you declare some variables in a global or local scope on a multi-person project, may be overridden by someone else accidentally with a variable of the same name, depending on the nature of the scope chain of the JavaScript function, You can use this technique to mimic a private scope, use an anonymous function as a "container," inside the container to access external variables, and the external environment to access variables inside the container, so (function () {...}) () internally defined variables do not collide with external variables, commonly known as "anonymous wrapper" or "namespace."

jquery uses this method to wrap the jquery code in the (function (window,undefined) {...} jquery code ...} (window), when you invoke jquery code in the global scope, you can achieve the protection of jquery internal variables.

JS Execute function immediately

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.