[removed] Creating Functions in a For Loop

前端 未结 3 868
既然无缘
既然无缘 2020-11-29 06:41

Recently, I found myself needing to create an array of functions. The functions use values from an XML document, and I am running through the appropriate nodes with a for l

3条回答
  •  自闭症患者
    2020-11-29 06:55

    I recommend picking up a book like JavaScript: The Definitive Guide to gain a deeper understanding of JavaScript in general so you can avoid common pitfalls like this.

    This answer also provides a decent explanation on closures specifically:

    How do JavaScript closures work?

    When you invoke

    function() { return i; }
    

    the function is actually doing a variable look-up on the parent call-object (scope), which is where i is defined. In this case, i is defined as 10, and so every single one of those functions will return 10. The reason this works

    (function(i){ return function(){ return i;}})(i);
    

    is that by invoking an anonymous function immediately, a new call-object is created in which the current i is defined. So when you invoke the nested function, that function refers to the call-object of the anonymous function (which defines whatever value you passed to it when it was invoked), not the scope in which i was originally defined (which is still 10).

提交回复
热议问题