"JavaScript programming lecture" Reading Notes-Chapter 2 Functions

Source: Internet
Author: User
Tags closure definition

2.1 analyze the definition of functions

The function definition is very simple, such as Function Square (x) {return x * X;}. The function name is square. In JS, all functions return values. Even if you do not use the return keyword, undefined is returned by default. Another point that needs to be emphasized is that everything in JS is a value, and the function is a value.

When the code is executed, all function definitions are scanned first, so you don't have to worry about whether the function definition will be called if it is written after the Execution Code. The preparations have been completed before execution.

Use the VaR keyword before defining a local variable. Otherwise, a global variable is defined. Variables defined in a function cannot be called outside the function. variables outside the function can be called at will within the function.

Another important concept in JS is 'stack '. When the code is executed to a function, the control of the Code is handed over to the function. After the function is executed, the control of the Code is handed over. The information should be returned to that place during execution. The information is stored in the 'stack'. The context (that is, the location where the execution is started) of each function when it is not called) will be stored in the 'stack. This also makes JavaScript flexible use of functions, such as functions as parameters and functions as return values. Of course, improper use may also cause problems:

View code

Function chicken () {return egg ();} function egg () {Return chicken ();} chicken (); // the stack is full due to an endless loop, stack Overflow occurs.

The following is an interesting example to illustrate the strong flexibility of JavaScript and the characteristics of all JavaScript values:

View code

VaR A = NULL; function B () {return "B" ;}( A | B) (); // obtain B after execution.

The closure issue. To be honest, this book is very rough. The closure is a difficult question for you to understand. There are many situations that you may struggle. I will check other people's information and try again.

Understanding of the closure part (read a lot of articles written in the garden and write down some of them)

First, it is pointed out that in JS functions, not only can a variable be defined, but also a function can be defined. When the function is executed, the internal variables of the function are transferred to the memory for corresponding operations,

When the function ends, the memory is released, and the variables in the function expire, and the closure can make the originally saved variables can be called repeatedly after the function ends. JS scope tells us

Internal access to the external, external access to the internal, but the closure can access the internal variables of the function outside the function. The following code details:

View code

// A closure definition is: if a function accesses its external variables, it is a closure. // At least if I have not understood the above, I think the following instances 1 and 2 do not reflect the characteristics of the closure. It should be // not a closure. // Instance 1var name = "zhangsan"; function showname () {// The variable name outside the function is called inside the function. VaR text = "my name is" + name; alert (text) ;}showname (); // instance 2 function outer (three) {var two = 2; function inner (one) {alert (three + (++ two) + one);} inner (1) ;}outer (3 ); // although this instance is also a variable in which the internal function calls the external function, it still does not belong to the closure. Run outer (3) multiple times, and the data is 7 at a time. The true closure instance is not changed. Example 3 // instance 3 function outer (three) {var two = 2; return function inner (one) {alert (three + (++ two) + one) ;}}var invoke = outer (3); invoke (1); invoke (1 ); // The internal function calls the variable of the external function, and the internal function is reflected in the form of a return value. This is a complete closure. // Call invoke (1) multiple times. The two variable does not disappear even though the previous functions have been completed. Instead, it accumulates with the next call.

The concept of closure is varied. In my understanding, closure is a state. When a function is used in a specific way (the code above is specific), it suddenly reaches

In this state, even if the function execution is complete, the internal variables of the function will not disappear, but will remain in the memory.

In addition, you can think of the function as an object in C. The variable in the function is the private member variable in the object. To call this private member, you need

The corresponding get and set methods. In JS, the return function inside the function provides corresponding functions.

All function parameters are optional. For example, you can easily run this line of code alert ("one", "two", "three"); however, you can only output 'one ', the following strings are ignored. The principle of variable function parameters is that if you write more parameters, it will be ignored.

Undefined. Therefore, there is no limit on the number of parameters.

2.2 tips

The most important function of a function is to avoid repetition. When some of your code is used repeatedly in a program, you should consider writing them into a function. However, functions must ensure the uniformity of functions. Do not encapsulate complicated functions into a function for the sake of feature, which greatly reduces the flexibility of calling functions. For example, when a Number has only one digit, it is used to adding 0, 5-> 05. This is a common method to write it in a function.

function zeropad(number,width){     var string = String(Math.round(number));    while(string.length<width){        string = "0" + string;    }    return string;}

In the preceding example, a width is used to determine the number before which a few zeros are required.

Pure function: when using a function, the same value is always returned for the same parameter without any side effects. (Digress: in fact, the book will describe some small concepts in length. This is actually a weakness for some people. I don't want to copy the notes in this series and do not want to copy the books to practice typing, try to write interesting things. I have always had a headache. How can this problem be solved)

Recursion: everyone should be familiar with recursion. Recursion has a characteristic. It is easy to understand some problems that can be solved by recursion, but the disadvantage is that the recursion efficiency is very low, and the lower the number of calls is. But sometimes, when the number of loop calls is small, recursion can use concise code to quickly solve the problem of messy thinking. The following example is also interesting. It is worth thinking: pass in a number and calculate whether it is obtained by adding 5 or multiplying 3. If it can return its computing path, if it does not exist, return null. 8-> (1*3) + 5;

View code

function findSequence(goal){    function find(start,history){        if(start == goal){            return history;        }else if(start > goal){            return null;        }else{            return     find(start + 5,"("+history+" + 5)")||find(start * 3,"("+history+" * 3)");        }            }    return find(1,"1");}alert(findSequence(1234));

Of course, the above calculation is not necessarily a shortest path, but a path.

 

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.