Closures: Line by Line explanation of “[removed] Good Parts” example?

后端 未结 4 702
花落未央
花落未央 2020-12-13 22:43

I\'m reading \"Javascript: The Good Parts\" and am totally baffled by what\'s really going on here. A more detailed and/or simplified explanation would be greatly appreciate

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 23:32

    It's all about closures. In the first example, "i" will be equal to "nodes.length" for every click event handler, because it uses "i" from the loop which creates the event handlers. By the time the event handler is called, the loop will have ended, so "i" will be equal to "nodes.length".

    In the second example, "i" is a parameter (so a local variable). The event handlers will use the value of the local variable "i" (the parameter).

提交回复
热议问题