JavaScript functions and scopes

Source: Internet
Author: User

Knowledge Content:

1.JavaScript function

2.JavaScript Scopes

Reference: JavaScript Advanced Programming

First, the functions in JavaScript

1. Definition of functions

After learning Python, the definition of the function is no longer unfamiliar, and the function is the core concept for any language. Through the function we can encapsulate any number of statements, and can invoke execution at any time anywhere. Functions in JavaScript Use function to declare definitions, and the basic syntax for a function is as follows:

1    functions}4 5//The following is an example of a function: 6 function Sayhi (name, message) {                         //define Functions 7     alert ("Hello" + name + ", "+}9 sayhi (" wyb "," good morning! ");  Calling functions 

or define the function in the following way:

1 Sayhi = function () {2     console.log ("Hello, world!" );  }4 5 sayhi ();  

2. Parameters and return values of functions

(1) Parameters of the function

The parameters that appear in the example above are called named parameters, like common parameters in Python, which are not explained in detail here.

The parameters of a function in JavaScript are internally represented by an array, which is always accepted by the function, without concern for the parameters contained in the array. The function can actually access the parameter array through the arguments object, thus obtaining each parameter passed to the function

Arguments object:

    • Access Parameters-Arguments[index]
    • Get number of arguments-length property
1 function Sayhi () {2     console.log ("Hello" + arguments[0] + "," + Arguments[1]); 3     console.log (arguments.length);   //Output incoming parameter number 4}5 6 sayhi ("wyb", "good morning!"); 7 8//Console.log () command-line output in the browser

The implementation of the arguments object allows the function to accept arbitrary parameters and implement the appropriate functions separately:

1 function Add () {2     if (arguments.length = = 1) {3         alert (arguments[0]);  4     } 5     else if (arguments.length = = 2) {6         alert (Arguments[0] + arguments[1]); 7     } 8} 9 Add (ten);         1011 Add (ten);  30

In addition, arguments objects can be used in conjunction with traditional named parameters:

1 function Add (NUM1, num2) {2     if (arguments.length = = 1) {3         alert (NUM1);  4     } 5     else if (arguments.length = = 2) {6         alert (NUM1 + arguments[1]); 7     } 8} 9 Add (+);         1011 Add (ten);  30

In the above program NUM1 is equivalent to arguments[0],num2 equivalent to arguments[1], and the value of arguments is always consistent with the value of the corresponding named parameter

Note: A named parameter without a value is automatically assigned a undefined value similar to a variable definition when it is not initialized; All parameters in JavaScript pass values, it is not possible to pass arguments by reference

(2) Return value

    • A function in JavaScript can or may not return a value, use return to return the return value
    • The function stops executing after the return and exits immediately, and the statement after the exit is not executed;
    • You can return multiple functions in a
    • Return can also be returned without any return value
1//functions with return value 2 function sum (NUM1, num2) {3     return NUM1 +} 5  6//Return statement does not perform a 7 function sum (NUM1, NUM2) {8     return NUM1 + num2; 9     alert ("statement after return will not execute");    }11 12//contains multiple return13 function diff (NUM1, num2) {if (Num1 < num2) {return num2- } else
             
               {num1-
              }21 22//return23 function Sayhi without any return value (name, message) {alert ("Hello" + name + "," +< c20> message);    
                    

3.JavaScript function Considerations

(1) JavaScript functions without overloading

Traditional overloads:

Overloading in Java and C + + is the ability to write two definitions for a function, as long as the two functions accept different types and quantities of parameters

There is no conventional overload in JavaScript, but JavaScript can make different reactions by checking the type and number of parameters in the incoming function, and can simulate overloads such as the following:

1 function Add () {2     if (arguments.length = = 1) {3         alert (arguments[0]);      } 5     else if (arguments.length = = 2) {6         alert (arguments[0] + arguments[1} 9 Add (10);//1011 Add (10, 20);      -

Basic functions of 4.JAVASCRIPT3

(1) General function

上面所有的函数均是普通函数
1 function func (ARG) {2     return True; 3} 

(2) anonymous function

A function without a name

1 var func = function(ARG) {2      return "Tony"}4 5 setinterval (function() {6      Console.log (123); 7}, )   

(3) Self-executing function

The program interprets execution from top to bottom, creates functions, and executes automatically

1 (function      console.log (ARG); 3}) (' 123 ')

Second, javascript scope

1.JavaScript Execution Environment

execution Environment: defines the data that variables and functions have access to, and determines their respective behavior. Each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in this object

After all code in an execution environment is executed, the environment is destroyed, and all the variables and function definitions stored therein are destroyed (the global execution environment is not destroyed until the application exits-for example, when the Web page or browser is closed)

function and execution environment: each function has its own execution environment, when the execution flow enters a function, the function's environment will be pushed into an environment stack, and after the function executes, the stack will eject its environment and return control to the previous execution environment.

2. Scope

What is a scope: the name used in a program code is not always valid/available, and the scope of the code that qualifies the name for its availability is the domain of the name.

    • Languages such as C/c++/c#/java are distinguished by a block of code that is scoped by code blocks
    • Python/javascript to function as a scope

About the scope of javascript: Each function in JavaScript has its own scope, and when a function is nested, a scope chain appears. When the inner-layer function uses a variable, it is based on the scope chain from the inner to the outer layer of the loop, and if it does not exist, the exception

1 public void Func () {2     if (1==1    {4         string name = "java"; 5         Console.WriteLine (name);            } 7     Console.WriteLine (name);            } 9 Func ()    
1 def func (): 2     if 1==1: 3         name = "Python" 4         print (name)            // normal operation 5     print (name)                // func () 8 print (name)                    //Error   
Function func () {    if (1==1) {        var name = "JavaScript";        Console.log (name);                Normal operation     }    console.log (name);                    Normal operation }func (); Console.log (name);                        Error    

3. Scope Chain

When code executes in an environment, a scope chain of variable objects is created

The role of a scope chain: guaranteed orderly access to all variables and functions that the execution environment has access to

About scopes and scope chains:

    • The scope of a function is created before the function is called
    • The scope of a function has a scope chain, and the scope chain is created before the function is called.
1//The scope of the function is determined before the function is called 2 name = "WYB" 3 functionFunc () {4 var name = "XXX"; 5 functionInner () {6 var name = "Ooo";            7 Console.log (name); Output: Ooo 8} 9 10Inner (11)}12 13Func (); name = "wyb" functionFunc () {var name = "XXX"n functionInner () {//var name = "Ooo"; Console.log (name);//output: xxx22}23 24Inner (25)}26 27Func ()-name = "wyb" functionFunc () {+//var name = "XXX";Inner () {//var name = "Ooo"; Console.log (name);//output: Wyb36}37  inner () functi }40 42  func () 43 44//The scope of the function exists scope chain scope chain is also created before the function is called the name = "wyb" On  func () {var name = "xxx" ; the function  inner () {$ var name = "ooo" ; console.log (name);//output: Ooo51 }52-return  inner;54 }55-var ret =  func ()  ret () All-in-a-name = "WYB" Functi On  func () {"var" name = "xxx" ; "N-function  inner () {//var name =" Ooo "; Console.log (name);//output: XX x66 }67-return  inner;69 }70-var ret =  func ()- ret () All-in-a-name = "WYB" function< span> func () { () {//var name = "Ooo"; Console.log (name);//output: wyb81 pan>}82 return  inner;84 }85-var ret =  func () ret ()       span>                 

Note the following issues:

1         name = "wyb" 2     function func () {3         var name = "xxx"; 4         function inner () {5                 //var name = "Ooo"; 6             Console.log (name);                    } 8         var name = "Tony"; 9         return }12-var ret = func () ret ()
         

The reason for the output of Tony is:

4. Local variables within the function are declared in advance

1//function internal Local variables will be declared in advance 2//When the interpreter, the function in the early generation of the scope chain at the same time to find all internal local variables 3//And then declare the variable  var xxoo in advance;  At this point the value of output Xxoo is undefined 4  5 function    } 8  9 func ()        //program directly error ten function     Console.log (Xxoo);     var xxoo = "666"}16-func ()//undefined  

JavaScript functions and scopes

Related Article

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.