I. Function definition
Mode 1. Normal way definition function
Function name (number of parameters N) {
function body
}
function Add (A, b) {return a+b;}
Method 2. Direct Volume definition function
var function name =function (number of parameters N) {
function body
}
var add=function (A, b) {return a+b;}
Mode three. constructor definition function
var function name =new function (parameter n, function body);
var add = new Function (' A, B ', ' return a+b; ');
Two. Scope of variables:
Global variables: Global domain and function domain
Local variables: within local function domains
<script type= "Text/javascript" >var a= "a"; function fn () {var b= "B"; alert (a); alert (b);} FN (); alert (a); ALELRT (b);</script>
Printed results: A,b,a We found the last alert (b) was not printed this is because the B definition in the function body can only be used within the function body
Special scopes
<script type= "Text/javascript" >var a= "a"; function fn () {alert (a); var a= "B"; alert (a);} Alert (a);</script>
Execution Result:
Undefined,b,a
Code Explanation:
* Read the code:
* * defines a global variable A and initializes it to "a".
* * defines a function, FN (), but it is not called (the code that describes the contents of the function does not run).
* * define local variable A, but not initialize.
* * to the above code, there are several variables in the current environment?
* * global variable A, with a value of "a".
* * local variable A, but no value.
* * when the function fn () is called:
* * Print Variable A: Nearest principle
* * local variable A, no value: The result is undefined.
* * print variable A, local variable a.
* * print variable A: global variable A in the global domain.
*
* Conclusion:
* * JavaScript defines all the variables in a code snippet at once, but does not initialize it.
* * JavaScript initializes the variable when it is run to the appropriate statement.
* &NBSP;
* * When the global variable has the same name as a local variable:
* * in the function field, only the local variable A is available.
Three ways to define functions in JavaScript & scope of variables