One solution to this problem found on the Internet is to use a function layer to avoid the problem blog. csdn. netmask narticledetails3899261, but it is still hard to understand .. Are there other methods to understand and solve it? Update: I installed a layer of functions, but I also avoided the online search. One solution to this problem is to use a layer of functions to avoid problems.
Http://blog.csdn.net/victorn/article/details/3899261
But is there any other way to understand and solve it?
Update: I installed a layer of functions and avoided them.
Reply: I'm glad to have a pure JS question.
1,
@ Yang coffeeIn JS, parameter passing does not involve parameter passing. In fact, this is not the case. There are two methods for passing parameters in JS:
By value and by sharing.
For example, in C, C ++, and Java, the parameter passing method is
By value and by reference.The former is the transfer value, and the latter is the transfer address. The same is true for Javascript. The former is the value transfer, and the latter is the address transfer.
By value is for the original data type, such as int and char, while By sharing and By reference are for advanced data structures such as Object and struct. We can imagine that an Object or struct cannot only PASS Parameters by passing values.
A simple example shows the difference between by reference and by sharing.
Var bar;
Var foo = bar;
Bar = {'key': 'value '};
Console. log (foo, bar );
In By sharing, foo is undefined, bar is {'key': 'value'}, and By reference should both be {'key': 'value '}.
2. In fact, LZ needs to understand this problem and scope in JS ).
When a function is created, it has three important built-in properties.
{
AO // records the variables and parameters in the function.
This // indicates this when this. xx is called.
Scope // a chain pointing to the outer function AO (which may be implemented through arrays during implementation ).
}
In JS, we often talk about Scope as follows: SCOPE = AO + scope.
Back to the closure issue:
If we write this program like this:
For (var I = 0; I Link [I]. onclick = function () {alert (I) ;}; // inner function
}
The SCOPE of the inner function is as follows:
{
AO
This // equals to link [I]
Scope // records pointing to the window, including the variable I we need
}
This for loop is executed immediately. When onclick is triggered, the inner function searches for variable I in AO + scope, but not in AO, the variable I in scope has become link. length.
Write this program using the closure we call:
// Here is the window scope
For (var I = 0; I
Link [I]. onclick = (function (I) {// outer function
Return function () {// inner function
Alert (I );
};
}) (I );
}
Analyze the SCOPE of inner function:
{
AO // no important infomation
This // we don't care it.
Scope // outer function and window scope
}
SCOPE of the outer function
{
AO // contains parameter I
This // don't care it.
Scope // window scope.
}
At this time, if the inner function is triggered, he will find the variable I from his AO and scope (AO and window scope of the outer function. we can see that the AO of the outer function already contains I, and for this for loop, there will be N (Function (){})()Created and executed. Therefore, each inner function has a specific outer function that contains variable I.
In this way, we can smoothly output 0, 1, 2, 3 .........
Conclusion: we can see that the closure is actually generated by Scope, so broadly speaking, All functions are closures.
In addition, this includes, This, function expression and function DeclarationThe difference is not described here.
3. Another method:
Use the bubble feature of the dom onclick event, that is @Xiiiiiin is a proxy.
Define onclick event listening on the parent node of the link dom node. The parameter is e (other names are also allowed, but there must be parameters ). In this case, we can know that the subnode is clicked through e.tar get, and we can also perform corresponding processing.
This is a better method. (Closures sometimes cause memory leakage ).
Let's say so much about it. It's time to go to work. To be useful to LZ. If anything is wrong, please criticize and correct it. I think the best way is to wrap a layer of functions.
Change the original
Alink. onclick = function () {alert (I )};
Changed:
(Function (I) {alink. onclick = function () {alert (I) };}) (I );
I think this is the best method. In js, only the function can divide the scope (a bit like python). if/else and for loops will not divide the scope, therefore, the six cycles in the original method reference the same variable I, because the closure is bound to the function.
After a layer is encapsulated, I is passed to the local scope of the inner anonymous function. Therefore, each of the six cycles creates an independent I (because it is six different scopes ). It's hard to understand your problem without reading the article.
You should include the following parameters:
Alink. onclick = (function (I ){
Return function (){
Alert (I );
};
}) (I );
In addition, I do not like the onxxx attribute.
PS: zhihu makes it difficult for me to paste code with a rich text editor. In addition, the last part of the answer disappears N times and cannot be seen.
This is related to the passing of parameters in JS functions and the assignment of events.
1. JS Functions Parameter passing is a parameter passing value without an address.
2. The onclick value should be Function DeclarationWhen an event is triggered Only one event parameter will be passedThe declared function.
If you use alink [I]. onclick = function () {alert (I );};
I is not a parameter of this anonymous function. It is included in the address. When the onclick event is triggered, the loop is over and I is the last value.
If you declare function ( I) {Alert (I );}
Then this I refers to the event. At this time, only the name of the event will pop up when the event is triggered.
Use alink [I]. onclick = (Function (_ I ){Return function () {alert (_ I );} }) (I);
Here is the execution External anonymous Functions, Return This anonymous function in the inner layerTo onclick.
Note: The outer function is executed immediately., With a parameter, We passed it, not the event trigger..
The inner function does not contain parameters.When the event is executed, the trigger will pass it an event value.
An anonymous function is generated for each I in the loop. I is used as a parameter of the generated anonymous function and is passed in.
When I = 2 in a loop, the function () {alert (2) ;}; is assigned to alink [2]. onclick, that is Alink [2]. onclick = function () {alert (2 );};
This is what we want.
PS: closure is just a method, not the core of solving the problem.
This method is equivalent to the following method, but the closure is not used below.
Var al = function (param ){
Return function (){
Alert (param );
}
}
Alink [I]. onlick = al (I );Er ...... In this example, I think about the variable scope. The key to this question is to clarify the JavaScript variable scope and scope chain. The previous answer does not seem to be clear.
This problem is mentioned in JavaScript: The Good Parts. Let's look at this example:
// BAD EXAMPLE
Var addActions = function (nodes ){
For (var I = 0; I <nodes. length; I ++ ){
Nodes [I]. onclick = function (e ){
Alert (I );
};
}
};
// END BAD EXAMPLE
The explanation is as follows:
The function is intended to give each event processor a different I. However, it fails because the event processor function is bound to the I itself, rather than the value of variable I during function construction.
The reason for this is that after reading JavaScript: The Definitive Guide, you will understand:
All JavaScript Functions are closures: they are all objects and are associated with the scope chain. Each time a JavaScript function is called, a new object is created for it to save local variables and add the object to the scope chain (in simple terms, the scope chain is the object list ).
In this bad example, function (e) {alert (I) ;}will be defined in the same function call, so they share variable I. That is to say, the I in their scope chain is the same I. That is, the scope chain associated with the closure is "active ".
JavaScript: The Good Parts also provides a solution:
Var addActions = function (nodes ){
Var helper = function (I ){
Return function (e ){
Alert (I );
};
};
For (var I = 0; I <nodes. length; I ++ ){
Nodes [I]. onclick = helper (I );
}
};
Explanation: Create an auxiliary function outside the loop, instead of creating a function in the loop.After reading this article, we all know the execution context of JavaScript. Here, I think the top answer is too obscure for the average person to understand.
Here I propose an interesting conjecture,
//----------------------------------------
// Paste the code
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Http://www.w3.org/1999/xhtml ">
Untitled document
Script
Var oUl1 = document. getElementById ('ul1 ');
// Alert (oUl1 );
Var aLi = document. getElementsByTagName ('lil ');
Var length = aLi. length;
For (var I = 0; I
{
ALi [I]. onclick = (function (index ){
Var y = I;
Return function (){
// Alert (index );
Alert (y );
};
}
) (I );
}
// Raise the conjecture that there is no cross-scope issue when the number of references increases by 1 to 2.
// The guess is correct.
Script
//------------------------------------
As you can see, the index buffer value is the method used by most people. This is a very reliable method, but few people can explain why, but use the so-called professional to confuse you.
//------------------------------------
This is also true. By accident, we can see the garbage collection mechanism and the conjecture raised by the number of references,
Under normal circumstances, if var y = I is used and then continues to be referenced in return fn, it can only be referenced to the last value, In most cases, the serial numbers 0, 1, 2... will only be saved by one variable, and you will not expect to save them again with another variable,
But now we use y to reference it again, so that the number of times is changed to 2,This so-called cross-scope does not exist. We can reference each value.
//----------------------------
Of course, this is just a conjecture, but it has been verified here. As for whether it can continue, we need to continue our investigation. Be a proxy.
Add the attribute of each node cyclically, and then bind an event to the outer elem.
You don't need to use closures to answer your questions professionally. You can answer technical questions in zhihu... Great