请教《javascript语言精粹》一书中关于闭包的一个例子

下面的文字摘自《javascript:The Good Parts》的closure一节,没看懂,秦歌翻译的那本中文版也看了,还是没明白这段文字说的啥?希望各位SF的朋友能用你自己的理解帮我解释一下:

  1. 为什么第一段代码没有达到目的,不是说内部变量可以读取函数外部变量的吗?读取不到正确的标号,那怎么会弹出节点的数量呢?这个节点数量是怎么获取到的?

  2. 为什么第二段代码可以修正第一段代码的错误,加一个匿名函数它到底起到了什么作用?

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:

https://img1.mukewang.com/5b9b682f0001cd8706310273.jpg

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:

https://img1.mukewang.com/5b9b68400001eca006130257.jpg

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.
扬帆大鱼
浏览 686回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript