Home >Web Front-end >JS Tutorial >javascript solutions to common closure problems_javascript skills

javascript solutions to common closure problems_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:42:291135browse


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute it
]

The above code is intended to be used every time Add an event to each div, that is, whenever the div is clicked, the corresponding serial number of the div will be displayed. But when we run the program, we will find that no matter which one we click, only 7 will be displayed. What is the reason for this? --This is the problem of closure
It turns out that in js, when defining a function within a function, closure appears. At this time, the variables in the outer function can be used in the inner function, even if the outer function ends. But when a loop occurs in the outer layer, if the loop variable is used in the inner layer function, the final value of this variable will be directly referenced.
Just like the above code demonstrates.
How to solve it.
You can use anonymous functions to solve this problem. Anonymous functions will brake execution. We can use this feature to create a scope and activate a variable to reference the outer loop variable.
As shown in the code:

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]

Because it is in the inner function As long as a loop variable appears, it will have a final value, so we use an anonymous function to stimulate a scope. Before entering the inner loop, another variable obtains the value of the loop variable. This idea is the essence of dealing with closure problems.
The following example: There is no obvious for loop at this time, but according to the above ideas, the problem can be solved immediately
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute it
]

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

补充:看到有网友这样解决了问题:

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

我个人的理解是 在进入内层循环之前 把id赋值给f,f在作为内层循环的参数,其思想应该是一样的.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn