下面的文字摘自《javascript:The Good Parts》的closure一节,没看懂,秦歌翻译的那本中文版也看了,还是没明白这段文字说的啥?希望各位SF的朋友能用你自己的理解帮我解释一下:为什么第一段代码没有达到目的,不是说内部变量可以读取函数外部变量的吗?读取不到正确的标号,那怎么会弹出节点的数量呢?这个节点数量是怎么获取到的?为什么第二段代码可以修正第一段代码的错误,加一个匿名函数它到底起到了什么作用?It is important to understand that the inner function has access to the actual variables of the outer functions and not copies in order to avoid the following problem:Code View:The add_the_handlers function was intended to give each handler a unique number (i). It fails because the handler functions are bound to the variable i, not the value of the variable i at the time the function was made:Code View:Now, instead of assigning a function to onclick, we define a function and immediately invoke it, passing in i. That function will return an event handler function that is bound to the value of i that was passed in, not to the i defined in add_the_handlers. That returned function is assigned to onclick.
添加回答
举报
0/150
提交
取消