I. Function definition
Mode 1. Normal way definition function
function name (parameter n) {
function body
}
function Add (A, b) {return a+b;}
Method 2. Direct Volume definition function
var function name =function (parameter 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 that the last alert (b) was not printed because B is defined in the function body only 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>
Operation Result:
Undefined,b,a
Code Explanation:
* Read the code:
* * Defines a global variable A and initializes it to "a".
* * Defines a function fn (), but not called (the code that describes the function's contents does not execute).
* * Define local variable A, but not initialize.
* * to the above code, there are several variables in the current environment?
* * global variable A, value "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 global domain.
*
Conclusion
* * JavaScript defines all the variables in a code snippet at once, but does not initialize.
* * JavaScript initializes the variable when it executes to the corresponding statement.
*
* * When global variables have the same name as local variables:
* * In the function field, only the local variable a is accessible.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Three ways to define functions in JavaScript & scope of variables