The following is the sample code for various methods:
Copy codeThe Code is as follows:
<Html>
<Head> <Body>
<Script type = "text/javascript">
/* Javascript-defined functions (declared functions) can be used in three ways: normal methods, constructor, and direct amount of functions. */
/* 1. Normal method function (param ){}*/
Function print (msg)
{
Document. write (msg, "<br/> ");
}
/* If the function does not contain the return statement, only the statements in the function body are executed and the undefined */
/* 2. constructor method: new Function ()*/
Var add1 = new Function ('A', 'B', 'Return a + B ');
/* 3. Create an untitled function by using the function method ,*/
Var result = function (x, y) {return x + y ;};
/* You can also specify the function name */
Var result2 = function fact (x) {if (x <1) return 1; else return x * fact (x-1 )};
Document. write ('Call the general method :');
Print ("Print ('Call the constructor method: add1 (5, 6 )');
Print (add1 (5, 6 ));
Print ("Print ("direct call Function Method: result (3, 4 )");
Var re = result (3, 4 );
Print (re );
Print ("Call the function direct quantity method: result2 (3 )");
Print (result2 (3 ));
Print ("Print ('function as data use ');
/* Functions can be used as data */
Function add (x, y) {return x + y ;}
Function subtract (x, y) {return x-y ;}
Function multiply (x, y) {return x * y ;}
Function divide (x, y) {return x/y ;}
Function operate (operator, operand1, operand2)
{
Return operator (operand1, operand2 );
}
// Computing (2 + 3) + (4*5)
Var I = operate (add, operate (add, 2, 3), operate (multiply, 4, 5 ));
Print ('(2 + 3) + (4*5) =' + I );
Print ("// Use the function quantity directly
Var operators = new Object ();
Operators ['add'] = function (x, y) {return x + y ;}
Operators ['substract '] = function (x, y) {return x-y ;}
Operators ['multiply'] = function (x, y) {return x * y ;}
Operators ['divide'] = function (x, y) {return x/y ;}
Operators ['pow'] = Math. pow;
Function operate2 (op_name, operand1, operand2)
{
If (operators [op_name] = null) return "unknown operator ";
Else return operators [op_name] (operand1, operand2 );
}
// Define "hello" + "" + "world"
Var j = operate2 ("add", "hello", operate2 ("add", "", "world "));
Var k = operate2 ("pow", 10, 2 );
Print (j );
Print (k );
Print ("</Script>
</Body>
</Html>
The running result is:
Call the general method:
--------------------------------------------------------------------------------
Call the constructor method: add1 (5, 6)
11
--------------------------------------------------------------------------------
Call the Function Method: result (3, 4)
7
Call the direct method of function: result2 (3)
6
--------------------------------------------------------------------------------
Use functions as data
(2 + 3) + (4*5) = 25
--------------------------------------------------------------------------------
Hello world
100