Basic functions for getting started with JavaScript (1)

Source: Internet
Author: User
Tags variable scope

Series of topics: getting started with JavaScript

In general, functions in JavaScript can:

◆ Assigned to a variable

◆ Attributes assigned as objects

◆ Passed into other functions as parameters

◆ Returned as a function result

◆ Create with words

Function object

1.1 create a function

A method of creating JavaScript Functions (almost nobody uses) is to use the new operator to act on the Function "Constructor ":

 
 
  1. <strong>var funcName = new Function( [argname1, [... argnameN,]] body );</strong> 

The parameter list can contain any number of parameters followed by the function body, for example:

 
 
  1. <strong>var add = new Function("x", "y", "return(x+y)");  
  2. print(add(2, 4));</strong> 

The result is printed:

6

But who will create a function in such a difficult way? If the function body is complex, it takes a lot of effort to splice this String. Therefore, JavaScript provides a syntax sugar, that is, to create a function using the literal volume:

 
 
  1. <strong>function add(x, y){  
  2.     return x + y;  
  3. }</strong> 

Or:

 
 
  1. <strong>var add = function(x, y){  
  2.     return x + y;  
  3. }</strong> 

In fact, such syntactic sugar is more likely to cause misunderstandings of programmers in the traditional field. The function keyword will call the Function to create a new object, and pass the parameter table and Function body to the Function constructor accurately.

Generally, an object is declared in the global scope (the scope will be detailed in the next section), but it is only a value to an attribute, such as the add function in the previous example, in fact, only an attribute is added to the global object. The attribute name is add, and the attribute value is an object, that is, function (x, y) {return x + y ;}, it is important to understand this point. The syntax of this statement is as follows:

 
 
  1. <strong>var str = "This is a string";</strong> 

No problem. They all Add a new attribute to the global object dynamically.

To demonstrate that functions, like other objects, exist in the JavaScript operating system as an independent object, let's look at this example:

 
 
  1. <strong>function p(){  
  2.     print("invoke p by ()");  
  3. }  
  4.    
  5. p.id = "func";  
  6. p.type = "function";  
  7.    
  8. print(p);  
  9. print(p.id+":"+p.type);  
  10. print(p());</strong> 

No error. Although p references an anonymous function (object), it can also have attributes, just like other objects. The running result is as follows:

Function (){
Print ("invoke p ()");
}
Func: function
Invoke p ()

1.2 function parameters

In JavaScript, function parameters are interesting. For example, you can pass any number of parameters to a function, even if the function is declared with no formal parameters, for example:

 
 
  1. <strong>function adPrint(str, len, option){  
  2.     var s = str || "default";  
  3.     var l = len || s.length;  
  4.     var o = option || "i";  
  5.      
  6.     s = s.substring(0, l);  
  7.     switch(o){  
  8.        case "u":  
  9.            s = s.toUpperCase();  
  10.            break;  
  11.        case "l":  
  12.            s = s.toLowerCase();  
  13.            break;  
  14.        default:  
  15.            break;  
  16.     }  
  17.      
  18.     print(s);  
  19. }  
  20.    
  21. adPrint("Hello, world");  
  22. adPrint("Hello, world", 5);  
  23. adPrint("Hello, world", 5, "l");//lower case  
  24. adPrint("Hello, world", 5, "u");//upper case</strong> 

The adPrint function accepts three form parameters when declaring: the string to be printed, the length to be printed, and whether to convert it to a case-sensitive flag. But when calling, we can pass a parameter, two parameters, or three parameters to adPrint in order (or even more than three parameters can be passed to it, it does not matter ), the running result is as follows:

Hello, world
Hello
Hello
HELLO

In fact, JavaScript is different from other compiled languages when processing function parameters. What the interpreter passes to the function is an internal value similar to an array, called arguments, this is initialized when the function object is generated. For example, when we pass a parameter to adPrint, the other two parameters are undefined. in this way, the adPrint function can process undefined parameters internally and make them public to the outside: we can process arbitrary parameters.

Let's use another example to discuss this magical arguments:

 
 
  1. <Strong> function sum (){
  2. Var result = 0;
  3. For (var I = 0, len = arguments. length; I <len; I ++ ){
  4. Var current = arguments [I];
  5. If (isNaN (current )){
  6. Throw new Error ("not a number exception ");
  7. } Else {
  8. Result + = current;
  9. }
  10. }
  11. Return result;
  12. }
  13. Print (sum (10, 20, 30, 40, 50 ));
  14. Print (sum (4, 8, 15, 16, 23, 42); // the magic number on Lost
  15. Print (sum ("new"); </strong>

The sum function does not have explicit parameters, but we can dynamically pass them to any number of parameters. How can we reference these parameters in the sum function? Here, the pseudo array arguments is used. The running result is as follows:

150
108
Error: not a number exception

Function Scope

The concept of scope is embodied in almost all mainstream languages. In JavaScript, it has its own particularity: The variable scope in JavaScript is effective in the function body, but has no block scope, in Java, we can define the subscript variable in the for loop block as follows:

 
 
  1. Public void method (){
  2. For (int I = 0; I <obj1.length; I ++ ){
  3. // Do something here;
  4. }
  5. // At this time, I is undefined.
  6. For (int I = 0; I <obj2.length; I ++ ){
  7. // Do something else;
  8. }
  9. }

In JavaScript:

 
 
  1. <Strong> function func (){
  2. For (var I = 0; I <array. length; I ++ ){
  3. // Do something here.
  4. }
  5. // At this time, I still has a value, and I = array. length
  6. Print (I); // I = array. length;
  7. } </Strong>

JavaScript Functions run in a local scope. The function bodies running in a local scope can access the variables and functions in its outer (possibly global. The JavaScript scope is the lexical scope. The so-called lexical scope means that its scope is determined when it is defined (during lexical analysis), rather than when it is executed, as shown in the following example:

 
 
  1. <strong>var str = "global";  
  2. function scopeTest(){  
  3.     print(str);  
  4.     var str = "local";  
  5.     print(str);  
  6. }  
  7.    
  8. scopeTest();</strong> 

What is the running result? Beginners may come up with the following answer:

Global
Local

The correct result should be:

Undefined
Local

Because in the definition of the function scopeTest, the undeclared variable str is accessed in advance before initialization of the str variable, so the first print (str) will return the undifined error. Why does the function not access the external str variable at this time? This is because when the lexical analysis ends and the scope chain is constructed, the var variable defined in the function is put into the chain, therefore, str is visible in the whole function scopeTest (from the first row to the last row of the function body). Because the str variable itself is undefined, the program is executed sequentially, to the first line, the returned value is undefined, and the second row is assigned a value, so the print (str) of the third row will return "local ".


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.