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

后端 未结 4 703
花落未央
花落未央 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:12

    It has to do with closure.

    When you do the thing in the bad example,

    when you click each node, you will get the latest i value (i.e. you have 3 nodes, no matter what node you click you will get 2). since your alert(i) is bound to a reference of variable i and not the value of i at the moment it was bound in the event handler.

    Doing it the better example way, you bound it to what i as at the moment that it was iterated on, so clicking on node 1 will give you 0, node 2 will give you 1 and node 3 will give you 2.

    basically, you are evaluating what i is immediately when it is called at the line }(i) and it got passed to parameter e which now hold the value of what i is at that moment in time.

    Btw... I think there is a typo there in the better example part... it should be alert(e) instead of alert(i).

提交回复
热议问题