JavaScript function Usage Description _ Basics

Source: Internet
Author: User
Tags anonymous closure

What are functions (function)
function sum (a,b) {
return a+b;
}
In fact, the popular saying is a name of the Code section, convenient reuse.
To be aware of:
1.Javascript function syntax, because Javascript itself is case-sensitive, so a function cannot write a function or function.
2.sum is the name of the function, this is not necessary, and so we will speak later.
3.return is returned, if not written, the return of the function is undefined. If you want to return multiple values, you can return the array or object (later)
Call to function

Let's talk about the basic invocation of a function.

var result = SUM (1,2)
Parameters of the function

I'm sorry to say that this is the focus of this article.
instance one, with less than the actual number of parameters defined
var result = SUM (1);
The result is Nan, which means that the value of parameter B is undefined, but does not give an error, which creates a bug.
instance two, with more arguments than the actual number of parameters defined
SUM (1,2,3,4,5)
The result was 3. More than the parameters were found to be ignored.
instance three, a function with no parameters
function args () {return arguments;}
Each function has a default array that is arguments. It is the default parameter for each function is []. If we call the function as follows
Args (1,2,3,4,5,6);
You will find that the value of arguments is [1,2,3,4,5,6]. This is easy, we can change the sum method above

function sum () {
var res= 0;
for (i=0;i<arguments.length;i++) {
Res+=arguments[i];
}
return res;
}

SUM (1,2,3,4);
The result is 10, and the SUM function is much more flexible. ^_^

Functions are data

This is one of the more important concepts in a function, that is, a function is a data. See an example
function f () {return 1;}
var f=function () {return 1;}
Both of these function definitions are the same.
typeof F;
The value of F is "function", so the JavaScript function is a data type. It has two important features to compare
1. It contains the code
2. Can be executed
See an example
var sum = function (a,b) {return a+b;}
var add = sum;
sum=undefined;
typeof sum;
typeof add;
Add (1,2);
We assign the sum of functions as a value to add, and we find that the sum does not affect the invocation of Add. So the function is a normal assignment.
anonymous functions (Anonymous functions)
In JavaScript, you do not have to write assignment code, such as
"ABCD" 1 [1,2,3]
This will not be an error, this data is called Anonymous. The same function as the data can also be anonymous
function (a) {return a}
the anonymous function has two functions
1. An anonymous function can be passed into another function as a parameter.
2. You can understand that running this anonymous function
These two functions are discussed in detail below.

callback function (Callback functions)

Because functions like other data can be assigned, deleted, copied, and so on, you can also pass functions as arguments to another function.
Instance One
function Invoke_and_add (a,b) {
Return a () +b ();
}
function One () {
return 1;
}
function two () {
return 2;
}
Invoke_and_add (one, two);
The result was 3;
Let's take a look at the use of anonymous functions.
Example Two
Invoke_and_add (function () {return 1;},function () {return 2;}) is passed directly into a function body without the function name.
We call Invoke_and_add a callback function.
We replaced the One,two two functions with an anonymous function.
With the above two instances, the callback function is defined as passing a function A to another function B, and this function B executes function A. Let's just say function A is called a callback function. Plainly, is the function that is called directly, executes another function in one function!
If there is no name, it is called an anonymous callback function

Function of callback function

There are three main
1. When a function is passed as a parameter, there is no need to define a name for the function, and the benefit is to reduce the global variable.
2. Save a lot of code.
3. Improve the performance of the program.

Self-invocation function (self-invoking functions)

The self invocation function is also a representation of an anonymous function, which is called directly after the definition. As follows

(

function () {
Alert (' haha ');
}
)()

It's kind of weird, but it's really simple.
The call function is easy to use and you don't have to define more global variables. Another benefit is that this function cannot be executed two times. It's a great fit to do the initialization work.
Many of the most famous JavaScript libraries use this feature in a very large number of source code, such as jquery, which I like.

Internal functions (Inner functions)

Consider a function as a value, and since a value can be defined in a function, it is also possible to put a function as data in a function. As follows:
function A (param) {
Function B (theinput) {
return theinput *2;
}
Return ' The result is ' +b (param);
}
I can write that.
var a = function (param) {
var B = function (Theinput) {
return theinput*2;
};
Return ' The result is ' +b (param);
};
The B function is in a function, which means that the B function cannot be accessed outside of the a function. So it's also called a private function.
A (2);
A (8);
B (2);
found that B (2) is undefined. It is also determined that it is really a private function.
There are many benefits to using internal functions.
1. There can be fewer global variables. Excessive use of global variables may result in excessive bugs due to naming conflicts
2. Private, you can design a better interface function for external access.

Returns a function with a value (functions that return functions)

The function has a return value that has been introduced in previous articles, and the function returns a undefine even if it is not written back.
Take a look at the return value as a function
functions a () { 
Alert (' a '); 
returns function () { 
  alert (' B '); nbsp
}; 

In this example, the A function executes alert (' a '), and it returns another function B. About the call to return B we can use that.
var newfunc = a (); 
Newfunc (); 
Execution result is alert A and alert B
If you do not want to assign a value to this function, you can also abbreviate the following
A () (); 
Self-overriding of the function

Because a function can return a function, that means you can replace an old function with a new one, and refine it based on the previous example.
A=a ();
The first time you run function A, alert A, run function a again, and alert B, this feature is very useful for initialization. This function a overrides itself to avoid invoking the initialization function at a later time (the last example is alert a).
Of course, we have an easier way to rewrite the A function, which is to rewrite it inside the a function to see the code
function A () {
Alert ("a")
A=function () {
Alert ("B");
}
}
Alert A is executed only on the first call to the A function, which executes alert B in a subsequent call
Here's a combination of examples from the previous sections
var c = function () {
function A () {
Alert (' a ')
}
Function B () {
Alert (' B ')
}
A ();
return b;
} ();//alert (' a ');
C ();//alert (' B ');
This example has the following points to note
1. A function, b function is an intrinsic function.
2. Return b Returns a reference to a function.
3. The child invocation function overrides function C.

If you can understand this example, with respect to internal functions, the function of the child call function and the return value of the function can be understood.

Closure (Closures) closures are a more difficult part of learning the following JavaScript scope (scope) before you learn about closures

Scope chain (Scope Chain)

Variables defined inside a function that are not accessible outside of a function, or that are defined in a code snippet (such as If,for), are not accessible outside of the code snippet.
var a = 1;
function f () {
var b=1;
return A;
}
f ();//a=1
b;//b Not defined
A is a global variable, and B is defined in the function f. So:
In the F function, both A and B can be accessed.
Outside the F function, a can be accessed, and B cannot be

Look again at an example
var a = 1;
function f () {
var b = 1;
function N () {
var c = 3;
}
}
If you define a function n in function f, the function n can access not only the C of its scope, but also the B and a of the so-called parent scope
That's the scope chain (scope Chain)
Lexical scopes (lexical scope)

In JavaScript, there is also a lexical scope (lexical scope), which means that a function generates its scope when it is defined, not when it is invoked, but by looking at an example.
Function F1 () {var a=1;f2 ();}
function F2 () {return A;}
F1 ();//a not defined
Let's look at the function F1, call the function F2, because the function local variable A is also in F1, may expect the function F2 also access a, but the fact is not the case.
Because this time the F2 function has been defined, and its scope does not have a been found. Whether it's a function F1 or a function f2, you can only access local or global variables.

use closure to destroy this scope chain (breaking the Chain with Closure)

Let's say, for example, that the closure is clear.
Instance 1

function f () {
var b= "B";
return function () {
return b;
}
}
function f contains the variable B, which is not possible to access B in the global scope, and the result is undefined (undefined).
Look at the return value of this function as a function. This new function can access variable B in the F range. Look at the following code
var n = f ();
n ();//access B
Because the function f itself is global, and the function it returns is a new global function, it can also access the scope of function F.

Instance 2
This example is the same as the previous example, but one of the differences is that function f does not return a function, but instead creates a new global variable n with the following code
var n;
function f () {
var B = "B";
N=function () {
return b;
}
}
So you can directly n () to access the variable B in function f

From 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 actually provide an excuse for external access to internal variables

When we create a function f that passes the arguments, this argument becomes the local variable of function f. We can create an internal function of F to return this argument.
function f (ARG) {
var n =function () {
return args;
}
arg++;
return n;
}
var m= f (123);
M ();//124

The application of closure in circulation

Recycling can easily cause some bugs, although the surface is normal.
Look at the following code
function f () {
var a = [];
var i;
for (i=0;i<3;i++) {
A[i] = function () {
alert (i);
return i;
}
}
return A;
}
var a= f ();
A[0] ()//3
A[1] ()//3
A[2] ()//3
To create a new loop, our goal is to create a new function for Each loop, and the function returns the sequence value of the loop. Let's look at the results of the above code
Are all 3 and we expect the result to be 1,2,3.
What is it about? We created three new closures, all pointing to the variable i. The closure does not remember the value of the variable I, it is only a reference to the variable i. At the end of the loop, the value of I is 3, so the result is 3.

Take a look at the correct wording.
function f () {
var a = [];
var i;
for (i = 0; i < 3; i++) {
A[i] = (function (x) {
return function () {
alert (x);
return x;
}
}) (i);
}
return A;
}
var a = f ();
A[0] ()//0
A[1] ()//1
A[2] ()//2
We used a closure to change the variable i to a local variable x, and the x variables were different values each time. If you do not fully understand the self invocation function, then you can understand the following
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 A;
}

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.