function
Function format
function getPrototyNames(o,/*optional*/ a){a = a || [];for(var p in o){a.push(p);}return a;}Caller
func.caller returns the function caller
function callfunc(){if(callfunc.caller){alert(callfunc.caller.toString());}else{alert("no function call");}}function handleCaller(){callfunc();}handleCaller();//Return handlercallfunc();//No function call, return null, execute "No function call"callee
Anonymous method recursive call
alert( (function (x) {if (x <= ) return ;return x * arguments.callee(x - );}()));//scope
Everyone is familiar with the scope. Today I will talk about the closure problem and understand the closure problem thoroughly.
<script>var global = "global scope";//This is the global scope function scope(){var scope = "local scope";//This is the local scope return scope;//The returned scope is a local variable}</script>1.: The defined global variables can also be accessed inside the function . When the defined local variable and global variable name are the same, the local variable will hide the global variable and will not destroy the value of the global variable.
var scope = "global scope";function f(){var scope = "local scope";return scope;}alert(f());//local scopealert(scope);//global scope;The above is indeed easy to understand, right?
2. Global variables can be declared without var , but local variables must be declared with var. If local variables do not use var declaration, the compiler will default to this as a global variable.
<span style="line-height: .; font-family: verdana, Arial, Helvetica, sans-serif; font-size: px; background-color: rgb(, , );"> </span> scope = "global scope";function f(){scope = "local scope";return scope;}alert(f());//local scopealert(scope);//local scopeHowever, global variables do not use var declarations, and are only available for non-strict mode. If strict mode is used, an error will be reported.
<script>"use strict";scope = "global scope";function f(){scope = "local scope";return scope;}alert(f());//local scopealert(scope);//local scope</script>Therefore, it is recommended that you do not omit var when declaring variables, as it can avoid unnecessary trouble.
3. It is okay to declare in advance . What is what is ahead of time.
<script>"use strict";scope;console.log(scope);var scope = "global scope";console.log(scope);</script>
This may be seen as the first one to print undefined. Yes, it has not been assigned a value yet. The following assignment can determine the global scope.
This is not wrong, but why is this happening? Shouldn’t a variable be defined before it can be used?
Here I will tell you about the scope chain. JavaScript is a lexical scoped language.
1. A scope chain is an object or linked list. This set of code defines the variables "in scope" of this code. When JavaScript needs to find the variable scope, it will develop and search from the first object in the chain. If the first object is scope, the value of this object will be directly returned. If it does not exist, it will continue to search the second object until it is found. If the variable is not found on the scope chain, an error will be thrown.
We can express this function chain as follows: Find scope->window (global object) and then the scope is defined. However, the assignment operation was not performed, and the assignment operation was performed later, so the value is undefined at this time.
4. This is more confusing. What is the printed value?
<script>"use strict";var scope = "global scope";function f() {console.log(scope);var scope = "local scope";console.log(scope);}f();</script>See this code: If you are careless, you may write the wrong answer:
1. gobal scope
2. Local scope
Analysis: Declare global variables. When in the function body, the first one represents global variable, so global is printed, and the second one defines local variables, covering the global scope, so local scope is printed.
Such analysis is completely correct in C# java. But the analysis here is indeed wrong.
This shows that before this problem, let’s look at a question first.
This sentence is very important: global variables are always defined in the program. Local variables are always defined within the body of the function that declares it and the functions it nests.
If you are working in a high-level language, you are getting exposed to JavaScript a little unsuitable for its scope definition. I am the same. Let's take a look at an example:
<script>var g = "global scope";function f(){for(var i=;i<;i++){for(var j=;j<;j++){;}console.log(j);}console.log(i);}console.log(g);f();</script>What is the result of printing?
You see that {} represents a statement block, and the statement block is in the scope of the same block, so you may guess that the j and i values have been released in memory, so the result must be undefined.
The real result may disappoint you.
Why did this happen? My expression started like you.
Check out the sentence I asked you to remember now. . . Global variables are always defined in the program. Local variables are always defined within the body of the function that declares it and the functions it nests.
To be precise, the parameters of the function also belong to the category of local variables. This sentence is also very important! ! !
That sentence roughly means that as long as a variable defined inside a function is valid within the entire function. So the result is not difficult to understand. Looking back at our question, do you understand?
The chain of action also has the following definitions:
1. The action chain is composed of a global object.
2. In the function body that does not contain nesting, there are two objects on the action chain. The first object defines the function parameters and local variables, and the second is the global object.
3. In a nested function body, there are at least three objects on the action chain.
When a function is defined, a scope chain will be saved.
When this function is called, it creates a new object to store its local variables and adds this object to the saved chain of action. At the same time, create a new longer chain of functions representing function calls.
For nested functions, when the external function is called, the internal function will be redefined again. Because every time an external function is called, the action chain is different. Internal functions have subtle differences every time they are defined. Each time the external function is called, the code of the internal function is the same, and the scope of the associated code is also different.
Closure
After doing it for so long, I finally got to talk about it, but let’s analyze the scope before.
<script>var nameg="global"var g = function f() {console.log(name);function demo(){console.log("demo="+name);}var name = "";function demo() {var name = "";console.log("demo=" + name);}function demo() {console.log("demo=" + nameg);}demo();demo();demo();};g();</script>We analyze according to the action chain:
Call demo0, demo0()->find name, not found ->f(), return
Call demo1, demo1()->Find name, find, return
Call demo2, demo2()->find nameg, not found ->f() to find nameg, not found ->window to find nameg, return.
Look at this example:
<script>function f(){var count = ;return { counter:function() {return count++;},reset:function(){return count = ;}}}var d = f();var c = f();console.log("d first call: "+ d.counter());//console.log("c first call: "+ c.counter());//console.log("c first call: "+ c.counter());//</script>As you can see in this example, I did a counting and zeroing operation.
Two object instances of f are created, each with its own scope chain, so their values do not affect each other. When c is called the second time, the count value is saved because the c object is not destroyed. Only after understanding this example will the following example be easier to understand.
Everyone should be very clear about this process. So now let’s look at the closure problem. I set four buttons and click each button to return the name of the response.
<body><script>function btnInit(){for(var i=;i<;i++){var btn = document.getElementById("btn" + i);btn.addEventListener("click",function() {alert("btn" + i);});}}window.onload= btnInit;</script><div><button id="btn">Btn</button><button id="btn">Btn</button><button id="btn">Btn</button><button id="btn">Btn</button></div></body>Click to run, but the result is all btn5;
We sat down with the analysis just now. First, we need to call the anonymous function -> Find i, not found -> btnInit(), and found i in the for loop. turn up. We know that only the function call is released is released, and the i in for is always visible, so the last i value is retained. So how to solve it.
To solve the problem that the i value is not always visible in the function, we need to use the function's nesting and pass the i value in it.
function btnInit(){for(var i=;i<;i++){(function (data_i) {var btn = document.getElementById("btn" + data_i);btn.addEventListener("click", function () {alert("btn" + data_i);});}(i));}}Looking at the modified code, first execute the first for and create an object. We first execute the anonymous function ->data_i, but not found ->function(data_i), and then execute for again to create an object. The closure rules say that they do not affect each other. So the correct result can be obtained.
The above is the JavaScript must-know must-know (9) function that the editor introduces to you. Speaking of the relevant knowledge about closure issues, I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!