How to Use nested functions in javascript

Source: Internet
Author: User

Nested functions are allowed in javascript:
<Html> <pead> <meta http-equiv = "Content-Type" content = "text/html; charset = gb2312 "/> <title> nested functions </title> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Remember this:
Nesting is actually a kind of loop. There are two handles in the loop to let us grasp: one is the termination condition and the other is the increment.

Nested functions are a little different from normal functions:
Since it is a nested function, it is to apply itself as a value to the function body. This requires the function to have a return value. The return statement is required.

Example:

Example 1:
Copy codeThe Code is as follows:
Function a (x ){
If (x <= 1) return 1;
Else return x * a (x-1 );
}

Example 1 is a nested function. Let's look at two handles: if (x <= 1) return 1; this is the condition for termination when x <= 1, else return x * a (x-1); this is incremental, and the parameter is reduced by 1 each nested call to function.
So this example can also be converted into a circular body as in example 2.

Example 2:
Copy codeThe Code is as follows:
Function a (x ){
If (x <= 1) return 1;
Else {
Var m = 1;
For (var I = 2; I <= x; I ++ ){
M * = I;
}
Return m;
}
}

As shown in example 2, nested functions implement such a loop.

Example 3:
Copy codeThe Code is as follows:
Function a (x ){
If (x <= 1) return 1;
Else {
X --;
Return (x + 1) * a (x );
}
}

For example 3, as long as we have identified two handles in the nested function, the nested function can be implemented wherever it is put. Obviously, this is not as good as Example 1.

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.