下面的文字摘自《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.
請教《javascript語言精粹》一書中關于閉包的一個例子
揚帆大魚
2018-08-08 11:10:06