JavaScript function expressions

Source: Internet
Author: User
Tags closure

First, the order

There are two ways to define a function: One is a function declaration and the other is a function expression;

1.1 Function declarations

function functionname (Arg) {     // function Body }

With regard to function declarations, an important feature is the function declaration promotion, which means that the function declaration is read before executing the code. This means that you can put the function behind the statement that called it. As shown below:

// the function declaration is read before the code executes function HelloWorld () {   console.log ("Hello World");}

1.2 Function expressions

var functionname=function(ARG) {      // body }

This form looks like a regular variable assignment statement, which creates a function and assigns it to the variable functionname. The function created in this case is called an anonymous function. Because there is no identifier following the function keyword.

A function expression, like any other expression, must be assigned before it is used, as the following code causes an error;

// error, not assigned value, function does not exist var helloworld=function() {    console.log ("Hello World");}

With a function expression, we can dynamically assign a value to a function expression, as in the following code:

var // Statement if // Conditions   helloworld=function// assignment       console.log ("Hello World");}    } Else {    HelloWorld=function// assignment       console.log ("Hello, World");}    }

Second, recursive function

Recursive function is in a function by the name of the call itself (and C # and other languages, so the core idea of the program is almost, just some differences in the syntax, learn a language basis, learning other will be much easier), to give a classic recursive interview questions, a number of rules as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34 ... What is the 30th digit number, implemented with a recursive algorithm, the code is as follows:

        function foo (n) {            if (n <= 0)                return 0;             Else if (n > 0 && N <= 2)                 return 1;             Else                return foo (n-1) + foo (n-2);        }

Although this function indicates that there seems to be no problem, the following code can cause it to go wrong:

        var foo1 = foo;         NULL ;        Console.log (Foo1 (34));

The above code first saves the Foo () function in the variable foo1, then sets the Foo variable to null, and the result points to the original function with only one reference left. However, when the next call to Foo1 () is made, because Foo () must be executed, and Foo is already null, it causes an error, in which case the Arguments.callee can be used to resolve the problem. Arguments.callee is a pointer to a function that is executing, so it can be used to implement recursive calls to functions

     function foo (n) {            if (n <= 0)                return 0;             Else if (n > 0 && N <= 2)                 return 1;             Else                return Arguments.callee (n-1) + Arguments.callee (n-2);        }

You can also use a named function expression to achieve the same result. For example:

        var foo = (function  f (n) {            if (n <= 0)                return 0; c10/>Elseif (n > 0 && N <= 2)                return 1;             Else                return F (n-1) + f (n-2);        });

Three, closed package

3.1 Closures are functions that have access to variables in another function scope, and the common way to create closures is to create another function inside one function. To understand closures, you must first understand the scope of special JavaScript variables. The scope of the variable is nothing more than two, global variables and local variables, and then write a few demos to express directly;

The global variables are read directly inside the function:

        var // define a global variable        function fn () {            /// function reads global variables directly inside         }        fn ();

Local variables cannot be read directly outside the function:

        function fn () {            var n = +;        }         // n is not defined

Here's a place to note that when declaring a variable inside a function, you must use Var, which, if it doesn't, becomes a global variable:

        function fn () {             = +;        }        fn ();         //  -

Sometimes we need to get the variables declared inside the function, so we can create another function inside the function using the usual way of creating closures:

        function fn () {            = +;             function fn1 () {                console.log (n);            }            FN1 ();        }         //  -

In the above code, the function fn1 is included inside the function FN, and all local variables inside the FM are visible to the fn1. However, in turn, the local variables inside the fn1 are not visible to FN. This is the "chain-scoped" structure that is unique to the JavaScript language, and the child objects look up the variables of all the parent objects one level at a level. Therefore, all the variables of the parent object are visible to the child object, and vice versa.

FN1 can read the FN internal variables, so long as the fn1 as the return value, which allows us to read the FN variable externally

        function fn () {            = +;             function fn1 () {                console.log (n);            }             return fn1;        }                var result=fn ();        //  -

In this case, the FN1 is the closure, and the closure is the function that can read the variables inside other functions. Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function". So, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.

3.2 Use of closures

        Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times. As shown in the following code:

 function   FN () {n  = 100< Span style= "color: #000000;"            >; Nadd  = function   () {n  + =            1 function   fn1 () {con            Sole.log (n);         return   fn1;         var  result = FN (); Result ();          // 100   // 101  

Note: Because the closure function carries the scope of the function that contains it, it consumes more memory than other functions, and excessive use of closures can lead to excessive memory consumption, so delete all unused local variables before exiting the function.

Iv. Block-level scopes

The syntax for anonymous functions for block-level scopes (also known as private scopes) is as follows:

(function() {     // block-level scope });

Wherever you need some variables temporarily, you can use a private scope, such as:

        (function  () {            varnew  Date ();             if (Now.getmonth () = = 0 && now.getdate () = = 1) {                alert ("Happy New Year");}        ) ();

Put the above code in the global scope, if the January 1 will be a "Happy New Year" blessing; this technique is often used outside of a function in the global scope to limit the addition of too many variables and functions to the global scope. In general, we should always add variables and functions to the global scope as little as possible. In a large application involving many developers, too many global variables and functions can easily lead to naming conflicts. By creating a private scope, each developer can use his or her own variables without worrying about messing up the global scope.

JavaScript function expressions

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.