This is the 12th day of my participation in Gwen Challenge
Nesting and recursion
Nested functions and scope chains
First let’s look at what a nested function is. A nested function is a function defined within another function.
Now that we know what a nested function is, what is a scope chain?
Inner function may be used in the process of the external function of the variable, then the inner function first will look for this variable in the current function, if can’t find continue to find the variable in the outer function, if can’t find, continue to look for in the upper function, we call this chain query relationship scope chain.
Let’s look at a specific example to help you understand:
<script>
var b = 10;
function f1(){
var a = 100;
function f2(){
console.log(a);
}
console.log(b);
f2();
}
f1();
</script>
Copy the code
Recursive calls
A recursive call is a special type of call in function nesting, which refers to a procedure that calls itself within a function.
Recursive functions are great for solving some problems, but they consume a lot of memory, so avoid using them in development.
Let’s look at a classic example of a recursive function: find the NTH term of the Fibonacci sequence
The Fibonacci sequence refers to a sequence like this: "1,1,2,3,5,8,13......" <script> function Fibonacci(n){if(n<0){console.log(" input error, n cannot be less than 0! ); } else if(n==0){ return 0; } else if(n==1){ return 1; } else if(n>1){ return Fibonacci(n-1) + Fibonacci(n-2); } } console.log(Fibonacci(10)); </script>Copy the code
The closure function
We can access variables outside of an embedded function, but we can’t access variables outside of an embedded function, but sometimes we need to use variables inside of an embedded function. At this point we can use closure functions. Closure functions have two characteristics:
- Closure functions can read variables inside a function from outside.
- Closure functions keep variables in memory at all times.
So how do closures work?
A common way to create a closure is to create another function inside a function and use the other function to access local variables inside that function.
Here’s an example:
<script> function f1(){ var times = 0; Var c = function(){return ++times; } return c; Var count = f1(); console.log(count()); console.log(count()); console.log(count()); console.log(count()); console.log(count()); </script>Copy the code
Closures are a mechanism for protecting private variables from outside interference by forming private scopes during function execution.
Intuitively speaking is to form an undestroyed stack environment.