Functions in javascript as values, javascript Functions

Source: Internet
Author: User

Functions in javascript as values, javascript Functions

Because the number of functions in ECMAScript is a variable, the function can also be used as a value, that is, not only can the function be passed to another function, but also can be returned as another function.

This function accepts two parameters. The first parameter is a function name, and the second parameter is a value passed to the function.

Function add (num ){

Return num + 10;

}

Var result = callFunction (add, 10 ){

Alert (result); // 20

}



Javascript function as parameter name

A simple example. Test environment: win7 + ie8 + chrome
<Script type = "text/javascript">
Function Add (x, y ){
Alert (x + y );
}
Function Sub (x, y ){
Alert (x-y );
}
Function CallFunc (Fun, x, y ){
If (Fun & (typeof Fun = "function ")){
If (x & y & (typeof x = "number") & (typeof y = "number ")){
Fun (x, y );
} Else {
Console. log (typeof x );
}

} Else {

}
}

CallFunc (Sub, 5, 3 );
</Script>

What is the value in the Function called by Javascript?

You can use global variables to set c as a global variable in other functions.

<Script language = "javascript">
Var c; // defines the global variable c outside the function.
Function A (a, B, c)
{
Var a = 2;
Var B = 3;
C = a * B; // If var is absent in c, it is the global variable.
Var Calcuate1 = document. getElementById ("Calcuate1 ");
Calcuate1.innerText = Calcuate1.innerText + c;
}

Function B (d, e, f)
{
Var d = 4;
// Problem:
Var e // How do I pay the value of C in Function A () to e?
E = c // assign the global variable c to e
Var f = d * e;
Var Calcuate2 = document. getElementById ("Calcuate2 ");
Calcuate2.innerText = Calcuate2.innerText + f;

}

</Script>

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.