"JavaScript Basics" calling function expressions immediately

Source: Internet
Author: User

In JavaScript, when each function is called, a new run context is created. Because the variables and functions defined within a function can only be interviewed inside. It's not going to work out there. The context provides a very easy way to create privacy.

The Makecounter function returns an anonymous function that can access the "private" variable I, as if it were a bit of "privileged". function Makecounter () {    //I can only be interviewed on the inside of Makecounter to ask for    var i = 0;    return function () {        console.log (++i);    };} Note that ' counter ' and ' counter2 ' have their own scope ' I ' var counter = makecounter (); counter (); Logs:1counter (); Logs:2var counter2 = Makecounter (); Counter2 (); Logs:1counter2 (); Logs:2i; REFERENCEERROR:I is not defined (it exists only in the interior of Makecounter)

In very many cases, you do not need to return multiple "instances" of the function. You only need a single case. Or in other cases, you may not need a return value.

The key to the problem

Now you define functions like function foo () {} or var foo = function () {}, so you get an identifier for a function. You can call it through (). such as Foo ().

Functions like this can be called by the following (), such as Foo (), because Foo is not a reference to a//function expression ' functions () {/*...*/} ') var foo = function () {/* ... */}//can only cross the back (), function expressions can be run, which is counterintuitive. function () {/* ... */} (); Syntaxerror:unexpected Token (

As you can see above, there is an exception.

When the JS interpreter encounters Functionkeyword in the global scope or function, it defaults to a function declaration rather than a function expression. Suppose you don't tell the interpreter exactly that an expression is a function declaration that has no name, so it causes a syntax error exception, because the function declaration requires a name.

By the way: functions, parentheses, syntax errors

Interestingly, suppose you specify a name for the function and put the parentheses behind it for a different reason. The parser will also throw a syntax error. When the parentheses are placed after the expression means that the expression is a function to be called, the parentheses are placed after the declaration and are completely separated from the preceding declaration. Represents only a grouping operator (as a control of a control priority).

<span style= "Font-weight:normal;" >//This function is valid on the syntax declaration. It's just a statement, followed by the parentheses are invalid,//Because the grouping operator needs to contain an expression function foo () {/* ... */} (); syntaxerror:unexpected token)//Now assume that you put an expression in parentheses, no exception thrown//But the function is still not running functions foo () {/* ... */} (1);//actually the equivalent of the following two: a is a function declaration, an unrelated expression function foo () {/* ... */} (1) </span>

Want to learn a lot about others. Please visit ecma-262-3 in detail. Chapter 5. Functions

Call table function up to now (Iife)

Fortunately, the above syntax errors can be easily repaired. The most extensive approach is to tell the parser that the function expression is enclosed in parentheses, because in JavaScript, parentheses cannot contain declarations. Based on this, when the parser encounters Functionkeyword, it parses it into an expression rather than a function declaration.

The following two types can be used to run a function expression immediately, using the function's run context to create//private (function () {/* ... */} ()); Crockford recommends this (function () {/* ... */}) (); But this one works very well.//from parentheses or force operators, the ambiguity of function declaration and function expression is eliminated, and when the parser is expected to be an expression, they can also be ignored, see the sample var i = function () {return 10;} (); True && function () {/* ... */} (); 0, function () {/* ... */} (); Suppose you don't care about the return value of a function or your code readability//You can save a byte.  By adding a unary operator!function () {/* code */} () in front of the function, ~function () {/* code */} ();-function () {/* code */} (); +function () {/* code */ } ();//There is another version number, but I'm not sure how it will be implemented with ' new ' keyword. Run is normal new function () {/* code */}new function () {/* code */} ()
Important points to note about parentheses

Especially in the "disambiguation" brackets (that is, the parentheses that enclose the function expression), it is not necessary (because the parser already thinks it is an expression). It's a good idea to use in assignments.

This parenthesis clearly implies that the function expression can be called immediately, and that the variable will contain the return result of the function. is not the function itself. This frees some people from the hassle of reading your code, because assuming that your function declaration is very long. You may want to scroll to the following to know if you have this function is called.

Generally speaking. Want to write a clear code. Technically, to prevent the parser from throwing a syntax error exception, writing clear code also needs to prevent other developers from throwing error exceptions at you.

Use closures to save state

The immediate function is invoked by passing the parameters. Calling a function that has a name identity and passing it a number of parameters at the same time is very similar.

No matter what defines a function inside a function, it can be used to access the arguments of the outside function and the variables of the outer function (such a relationship is called a closure), and an immediate function expression can be called "lock" value and save state value.

If you want to learn a lot of other things about closures, read closures explained with JavaScript.

The following example 2 and Example 3 will run as you expect, and a very big drawback to running the function expression immediately is that it is anonymous or unnamed.

<! DOCTYPE html>




"JavaScript Basics" calling function expressions 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.