Basic knowledge of javascript Functions

Source: Internet
Author: User
In fact, it is simply a code segment with a name to facilitate reuse. What is a Function)
Function sum (a, B ){
Return a + B;
}
In fact, it is simply a code segment with a name to facilitate reuse.
Note that:
1. Javascript function syntax, because Javascript itself is case-sensitive, Function cannot write FUNCTION or function.
2. sum is the name of the function, which is not required. We will discuss it later.
3. return is returned. If no value is written, the return value of the function is undefined. If multiple values are to be returned, an array or object can be returned (later)
Function call

The following describes the basic function calls.

Var result = sum (1, 2)
Function Parameters

Sorry, this is the focus of this article.
Instance 1. The number of parameters is less than the number of actually defined parameters.
Var result = sum (1 );
The result is NaN, which indicates that the value of parameter B is undefined, but no error is reported, which virtually creates a bug.
Instance 2: more parameters than actually defined parameters
Sum (1, 2, 3, 4, 5)
Result 3: more parameters are ignored.
Example 3: functions without Parameters
Function args () {return arguments ;}
Each function has a default array named arguments, which is the default parameter [] of each function. If we call the function as follows:
Args (1, 2, 3, 4, 5, 6 );
The value of arguments is [1, 2, 3, 4, 5, 6]. This is easy. We can modify the sum method above.

Function sum (){
Var res = 0;
For (I = 0; I res + = arguments [I];
}
Return res;
}

Sum (1, 2, 3, 4 );
The result is 10. This sum function is much more flexible. Pai_^

Functions are data

This is an important concept in a function, that is, a function is a data. Let's look at an example.
Function f () {return 1 ;}
Var f = function () {return 1 ;}
The two function definitions are the same.
Typeof f;
The value of f is "function", so Javascript Functions are data types. It has two important features:
1. It contains code
2. executable
Let's look at an example.
Var sum = function (a, B) {return a + B ;}
Var add = sum;
Sum = undefined;
Typeof sum;
Typeof add;
Add (1, 2 );
We assigned the sum function as a value to add, and found that deleting sum does not affect the calling of add. So the function is a normal value assignment.
Anonymous Functions)
In Javascript, you do not need to write the value assignment code, such
"Abcd" 1 [1, 2, 3]
In this way, no error is reported. The data is called Anonymous. The same function can also be anonymous as data.
Function (a) {return}
Anonymous functions have two functions.
1. You can pass an anonymous function as a parameter to another function.
2. You can understand how to run this anonymous function.
The functions of these two functions will be discussed in detail below.

Callback Functions)

Because functions can be assigned, deleted, copied, and so on like other data, they can also be passed into another function as parameters.
Instance 1
Function invoke_and_add (a, B ){
Return a () + B ();
}
Function one (){
Return 1;
}
Function two (){
Return 2;
}
Invoke_and_add (one, two );
The result is 3;
Let's take a look at the usage of anonymous functions.
Instance 2
Invoke_and_add (function () {return 1 ;}, function () {return 2 ;}), directly transmits a function body without a function name.
We call invoke_and_add as the callback function.
We replaced one and two functions with anonymous functions.
Through the above two instances,The callback function is defined to pass A function A to another function B, and function B executes function. Function A is called A callback function. To put it bluntly, it is a function directly called by a person, and another function is executed in one function!
If there is no name, it is called an anonymous callback function.

Function of callback

There are mainly three
1. When a function is passed as a parameter, you do not need to define a name for the function. This reduces global variables.
2. Saves a lot of code.
3. Improved Program performance.

Self-invoking Functions)

A self-called function is also a form of expression of an anonymous function, which is called directly after being defined. As follows:

(

Function (){
Alert ('hahaha ');
}
)()

It looks weird, but it is really simple.
You can call a function easily without defining more global variables. Another benefit is that this function cannot be executed twice. It is very suitable for initialization.
This feature is used in many well-known javascript libraries, such as my favorite Jquery.

Inner Functions)

Think about using a function as a value. Since a value can be defined in a function, it is not necessary to put the function as data. As follows:
Function a (param ){
Function B (theinput ){
Return theinput * 2;
}
Return 'the result is '+ B (param );
}
It can also be written in this way.
Var a = function (param ){
Var B = function (theinput ){
Return theinput * 2;
};
Return 'the result is '+ B (param );
};
Function B is in function a, which means that function B cannot be accessed outside function. So it is also called a private function)
A (2 );
A (8 );
B (2 );
B (2) is not defined. It is determined that it is indeed a private function.
There are still many advantages for using internal functions.
1. There can be fewer global variables. Excessive use of global variables may result in too many buckets due to name conflicts.
2. Private, better interface functions can be designed for external access.

Function (Functions that Return Functions)

In the previous articles, we have introduced that a function must have a return value. Even if no return is written, the function will return an undefine.
Next let's take a look at how the returned value is a function.
Function (){
Alert ('A ');
Return function (){
Alert ('B ');
};
}
In this example, function a executes alert ('A') and returns another function B. The call to return B can be used in this way.
Var newFunc = ();
NewFunc ();
The execution result is alert a and alert B.
If you do not want to assign a value to call this function, you can also abbreviated it as follows:
A ()();
Function Rewriting

Because a function can return a function, it means that a new function can be used to replace an old function. Based on the previous example, we can improve it.
A = ();
When function a is run for the first time, alert a is used. When function a is run again, alert B is used. This function is very useful for initialization. This function a overrides itself to avoid calling the initialization function later (alert a in the previous example ).
Of course, we still have a simpler method to rewrite function a, that is, to rewrite function a in order to look at the code.
Function (){
Alert ("")
A = function (){
Alert ("B ");
}
}
Alert a will be executed only when function a is called for the first time. In future calls, alert B will be executed.
The following is a comprehensive example based on the previous sections.
Var c = function (){
Function (){
Alert ('A ')
}
Function B (){
Alert ('B ')
}
A ();
Return B;
} (); // Alert ('A ');
C (); // alert ('B ');
Note the following points in this example:
1. function a, function B is an internal function.
2. return B returns a reference to a function.
3. The sub-call function overrides Function c.

If you can understand this example, we can understand all the internal functions, subcalls and functions whose return values are functions.

The closure (Closures) closure is a difficult part. Before learning the closure, you should first learn the Scope of the following Javascript)

Scope Chain)

Variables defined in the function cannot be accessed outside the function, or the variables defined in the Code segment (such as if, for) cannot be accessed outside the code segment.
Var a = 1;
Function f (){
Var B = 1;
Return;
}
F (); // a = 1
B; // B is not defined
A is a global variable, while B is defined in function f. Therefore:
In function f, both a and B can be accessed.
In addition to function f, a can be accessed, while B cannot.

Let's look at another example.
Var a = 1;
Function f (){
Var B = 1;
Function n (){
Var c = 3;
}
}
If function n is defined in function f, function n can not only access c in its own scope, but also access B and a in the so-called parent scope.
This is Scope Chain)
Lexical Scope)

In Javascript, there is also a Lexical Scope, which means that the function generates its Scope when it is defined, rather than when it is called, let's take a look at the example.
Function f1 () {var a = 1; f2 ();}
Function f2 () {return ;}
F1 (); // a is not defined
First, let's look at function f1 and call function f2. Because the local variable a of function f1 is also in function f2, we may expect function f2 to access function a, but this is not the case.
This is because the f2 function has been defined, and its range is not found as. Whether it is function f1 or function f2, only local variables or global variables can be accessed.

Use closures to break the Chain with Closure)

Let's illustrate the closure.
Instance 1

Function f (){
Var B = "B ";
Return function (){
Return B;
}
}
Function f contains variable B, which cannot be accessed in the global scope. The result is undefined ).
Let's take a look at the return value of this function as a function. This new function can access variable B in the f range. See the following code:
Var n = f ();
N (); // access B
Because function f itself is global, and the function returned by it is a new global function, it can access the scope of function f.

Instance 2
The result of this example is the same as that of the previous example, but it is a little different. function f does not return a function, but creates a global variable n. The Code is as follows:
Var n;
Function f (){
Var B = "B ";
N = function (){
Return B;
}
}
So we can directly use n () to access variable B in function f.

Through the above two examples, we can say that when a function points to its parent scope, its function is to point to a local variable, it can be called a closure.
Closures provide an excuse for external access to internal variables.

When we create a function f that passes the parameter, this parameter becomes a local variable of function f. We can create an internal function of f to return this parameter.
Function f (arg ){
Var n = function (){
Return args;
}
Arg ++;
Return n;
}
Var m = f (123 );
M (); // 124

Application of closures in Loops

Recycling can easily cause some bugs, although the surface is normal.
See the following code:
Function f (){
Var a = [];
Var I;
For (I = 0; I <3; I ++ ){
A [I] = function (){
Alert (I );
Return I;
}
}
Return;
}
Var a = f ();
A [0] (); // 3
A [1] (); // 3
A [2] (); // 3
To create a new loop, we create a function for each loop. The function returns the Sequence Value of the loop, that is, I. Let's take a look at the running results of the above Code
They are all 3. The expected result is 1, 2, 3.
Why? We have created three closures, all pointing to variable I. The closure does not remember the value of variable I. It is only a reference to variable I. After the loop ends, the I value is 3, so the result is 3.

Let's take a look at the correct method.
Function f (){
Var a = [];
Var I;
For (I = 0; I <3; I ++ ){
A [I] = (function (x ){
Return function (){
Alert (x );
Return x;
}
}) (I );
}
Return;
}
Var a = f ();
A [0] (); // 0
A [1] (); // 1
A [2] (); // 2
We use another closure to change variable I to the local variable x, which is a different value each time. If you do not fully understand the self-called function, you can understand it as follows.
Function f (){
Function makeClosure (x ){
Return function (){
Return x;
}
}
Var a = [];
Var I;
For (I = 0; I <3; I ++ ){
A [I] = makeClosure (I); // makeClosure, used to remember the value of I.
}
Return;
}

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.