xTable of Contents [1] Function declaration method [2] Function call Way [3] The difference between the two ways of declaring
Function: A code block that can be reused to assemble code that completes a particular function.
-------------------------------------
First, how the function is declared (created)
A. Basic syntax
function keyword
function name ([parameter 1],[parameter 2] ...) {
function body
[Retrun]//return value
}
function Math () { var num1=parsefloat (Prompt ("Please enter", "")); var num2=parsefloat (Prompt ("Please enter", "")); var operator=prompt ("Please enter Operator", ""); var result; Switch (operator) {case "+": result=num1+num2; break; Case "-": result=num1-num2; break; Case "*": result=num1*num2; break; Case "/": result=num1/num2; break; Default: result= "wrong input"; } return result; } Alert (Math ());
B. The form of the literal definition (anonymous function)
var variable =function ([parameter 1],[parameter 2] ...) {
function body
[Retrun]//return value
}
var fun=function () { var num1=parsefloat (Prompt ("Please enter", "")); var num2=parsefloat (Prompt ("Please enter", "")); var operator=prompt ("Please enter Operator", ""); var result; Switch (operator) {case "+": result=num1+num2; break; Case "-": result=num1-num2; break; Case "*": result=num1*num2; break; Case "/": result=num1/num2; break; Default: result= "wrong input"; } return result; } Alert (fun ());
C. Declaring in object form (infrequently used)
The New keyword.
var variable =new function ([parameter 1],[parameter 2] ..., "function body");
var fun=new Function (Alert ("330141830")) fun ();
-------------------------------------
Second, the function calls the way
A. Function name (), variable name ();(already shown in previous code)
B. (function () {alert ("Backing Net");}) (); () in the meaning of this parenthesis is to run a function. The following code is different between parentheses and no parentheses
1. function calls without parentheses
<! DOCTYPE html>
Results:
2, parentheses when function calls
<! DOCTYPE html>
Results
-------------------------------------
Iii. differences between the two forms of declaration (A and B types)
1. If the two functions are named the same, the previous function will be overwritten by the subsequent one.
2. Functions that are declared in basic syntax are loaded into memory for later use when the code is running.
However, a function named in the literal form is assigned when it is executed.
3. Functions in different <script></script> blocks, when used and called, should be defined first and then executed.
The Declaration and invocation of JavaScript functions