The formal parameter closure of the function's argument function js

Source: Internet
Author: User
Tags variable scope

Arguments and formal parameters of a function
# Optional Parameters
```
if (a = = = undefined) a = [];
```
Equivalent to
```
A = a | | [];
```
These two sentences are completely equivalent, except that the latter need to declare a in advance.
If the parameter is not passed in, the remaining padding undefined
Optional formal parameters: Use the annotation/*optional*/to emphasize that the parameter is optional, and you want to put it at the end, otherwise you will be using null or undefined as a placeholder for incoming
# Variable long argument list
# callee and Caller
Callee is the function currently executing for the reference
Caller refers to the function that is currently executing the function
# use an object property as an argument
```
>
> function e (o) {
... return o.object;
... }
Undefined
> e;
[Function:e]
> var a = {object:33};
Undefined
> E (a);
33
>
```
# function as a value
function can pass in another function as a value

# Custom Function Properties
Function properties can be customized
'
O.A = 3;
function O () {
return o.a;
}
'
![ Enter a description of the picture here][1]
# as a function of a namespace
variables declared in a function are visible throughout the body of the function (including in nested functions) and are invisible outside the function. A variable that is not declared within any function is a global variable. is visible throughout the JS program. In JS, you cannot declare variables that are visible only within a block of code. So it's often simple to define a function as a temporary namespace. Variables defined within this namespace will not contaminate the global namespace. The
is precisely because if the variable is defined at the global time, the pollution of the variable will occur, and the pollution to the global variable (well, this is the pit of the dynamic language) causes some unknown errors. So, put the variable in the function, make a call, so that its variables to pollute its global space, there is a conflict of variables (especially in the browser environment, it is very easy to cause a variety of unknown errors, so you must do)
# # After the function is defined directly call the function
'
(
function () {
return 333;
} ()
);
'
Plus () is necessary because if the JS interpreter is not added () and the function declaration is interpreted by a function declaration, the JS interpreter does not allow an anonymous function declaration to be created, so an error is made.
Plus () becomes a function expression, and the JS interpreter runs to create an anonymous function expression
# closure
finally closed. (Seriously, Σ (° °| | |) ︴)
(This is the most difficult place, is the basis of functional programming, but also can learn JS the most critical place ....) Of course, ES6 also has a nasty arrow function.
Closures are an important foundation for their functional programming
and the lexical scope that JS uses as in other languages, that is, the execution of a function depends on the scope of the variable, the scope is determined at the time of the function definition, not the
That is, the internal state of the function object of JS contains not only the code logic of the function, but also the current scope chain (the scope of the variable is passed down, the scope chain of the variable is looked up at the time of the search, until the top of the function) the function object can be interrelated by the scope chain. Variables inside the function body can be stored inside the function scope * *, that is, closures
> very old term, meaning that function variables can be hidden within the scope chain, so it looks like the function will wrap the variables together.

# # How to define a scope chain
The scope chain is a list of objects, each time a JS function is called, a new object is created to hold its local variables, the object is added to the scope chain, if the function returns, the bound object is removed from the scope chain, if there is no nested function, there is no object whose reference points to the binding. The garbage collection mechanism of the JS interpreter is not timed, it is not deleted immediately when there is no full reference, if the nested function is defined, each nested function corresponds to a scope chain, and the scope chain points to a variable bound object. If these nested function objects are saved in an external function, they will also be recycled as garbage as they are pointing to the variable binding object, and if the function defines a nested function and returns it as a return value, or is stored in a property somewhere, an external reference will point to the nested function. That is, it will not be garbage collected, and objects bound by its variables will not be recycled as garbage.
The associated scope chain is not deleted after the > function is executed, and the delete operation occurs only when there is no reference.

! [Enter a description of the picture here] [2]

# # Description of the stack
Original stack
Stack top window
Execute the following JS script
```
function A () {
function f () {
return 333;
}
return F;
}
A () ();
```
Stack Top A→window
Start call, execute to return
Discovery needs to call F
Continue adding stacks
Stack Top F→a→window
F eject F after execution
Proceed to a, execution complete popup A
Final Execution Complete Popup window

Forget the text explanation is too weak, directly on the code
```
var scope = "Global scope"; A global variable
function Checkscope ()
{

var scope = "local scope"; Define a local variable

function f ()
{
return scope; Returns the value of scope in a variable scope
}

return f (); return this function
}
```
Call this function
```
Checkscope ();
"Local Scope"
```
Then execute this
```
var scope = "Global scope"; A global variable
function Checkscope ()
{

var scope = "local scope"; Define a local variable

function f ()
{
return scope; Returns the value of scope in a variable scope
}

return F; return this function
}
```
Continue calling function
```
Checkscope () ();
"Local Scope"
```
# # What's the use of closures
Look at a function Uniqueinteger () Use this function to track the last return value
```
var Uniqueinteger = (
function () {
var count = 0;
return function () {return count++}
}()
);
```
You use closures like this.
```
Uniqueinteger ();
0
Uniqueinteger ();
1
```
Each return is its last value and adds 1 to the value directly
As for why to write this, if you do not use closures, then the malicious code can casually reset the counter.
```
Uniqueinteger.count = 0;
function Uniqueinteger () {
return uniqueinteger.count++;
}
```
Like this, you can simply reset the value of its count directly by assigning it.
And if a closure is used, there is no way to modify it as a private state, nor does it cause a conflict of variables within a page, or is its overwrite.
# # # immediately called function
```
var a = (function C () {
var a = 1;
a++;
Console.log (' already executed ');
return function B () {return a++};
}())
```
Well, I'll probably explain this code.
First of all, explain the outermost parenthesis, because if there is no parentheses, then this is an assignment statement, an anonymous function is assigned to the variable A, is actually completed in memory of the stack in the variable a point to the anonymous function store the address of the space, if there is parenthesis, is actually telling the JS interpreter this is a statement, JS execution is required to eliminate the effect of its function. (PS; it seems that Firefox does not add, it can also run normally) execution and references are below the relationship.
And then, the final parenthesis, which represents its execution, because the JS parser resolves () to the function name in front of the call, similar to the operator. But it is not actually an operator, because it is possible to pass values to it, note that this is to save the result of its execution in the heap, and to complete its point
After that, when the direct input A;, actually executes and completes a call, its return value is function B, the function B completes a reference, that is, variable a refers to function B, because of its referential relationship, that is, the stack of variable A is saved as the return result of its function A, (because it is not an object, if write a () Represents the object returned after the function a call is saved in the stack, and then the contents of the stack is called again, because it is saved, there is no application relationship, so after completion of the direct garbage collection, because it holds the scope chain of function B, and function B's scope chain is inherited from function a scope chain, However, because the scope chain of function A does not have a reference that causes it to be garbage collected after it is executed (when there is no variable pointing). So, the value of the function is saved in function B, if the function C is modified this time the function C does not affect the save in function B, because the variable list of its function C has been destroyed,
Finally, the reference to the nested function continues to be discussed, because its parent function has been destroyed, but the nested function is referenced, (note: Because its parent has not, so is another new heap space, to store its function c return result, note is the return result, not function B) at this time the other specified variable to save its results, Regardless of the number of variables specified to save their results, * * are new space execution, no interference * *, detailed see below, continue to discuss
> 1. If it is () (), it will be garbage collected
> 2. PS also needs to note a little bit because it refers to the value of result, not its

Finally, this can be done with the variables stored in the function, seemingly called memory?

So, with heaps and stacks, it's good to understand closures.

# # # Go ahead and see the code #
```
function count () {
var n = 0;
return {
Count:function () {return n++;},
Reset:function () {n = 0;}
};
}
```
```
var c = count (); var d = count ();
Undefined
```
In the separate execution of the next
```
C.count ();
0
D.count ();
0
C.count ();
1
D.count ();
1
C.reset ();
Undefined
C.count ();
0
D.count ();
2
```
This reflects its non-impact, indicating that its father was recycled, causing its children to create a piece of new memory space in the heap, and to complete its point, do not interfere with each other.
* * Its scope chain does not interfere with each other * *


# # # Use getter and setter to complete its closures
```
function count (n) {
return {
Get Count () {return n++;},
Set count (m) {
if (M >= N)
n = m;
Else
throw new Error (' Please enter a correct value ');
},
};
}
```
This doesn't have to be explained, it's simple.

# # # Two closures defined in the same scope chain
```
function Test1 () {
val = value = 111;
This.test = function () {return value-1;};
This.test2 = function () {return value + 1;};

}
```
This is also a two-role chain field
However, it is necessary to execute its o.test1 () first, because its method inside its function, must first execute, completes its method to add, otherwise will error,
```
Ee.test is not a function
```
Hint that this method cannot be found,
Because the execution
```
Ee.test1 = test1;
function Test1 ()
```
It is simply assigned and cannot be viewed, so it cannot be used
So, do it first, let the method be added.
```
Ee.test1 ();
Undefined
Ee.test ();
110
Ee.test2 ();
112
```
This is the two closures, which are parallel to each other and inherit from their father, but not influenced by their fathers, it's amazing, (*@ο@*)
> Ding found a strange and strange East https://us.leancloud.cn seems to be able to understand some of the current level

# # # questions about this
This is the object that the method is used to display in the parent closure.
But the son is not necessarily.
```
function Test1 () {
val = value = 111;
This.test = function () {return this.x-1;};
This.test2 = function () {return this.x + 1;};
}
```
Take a look.
```
Ee.test ();
4443
```
It's embarrassing.
All right. Can only say that is generally not used
It's usually written like this
```
var = this;
```
Save its value in a self

[1]: Https://www.iming.info/wp-content/uploads/2018/07/1-113.png
[2]: Https://www.iming.info/wp-content/uploads/2018/07/1-114.png

The formal parameter closure of the function's argument function js

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.