Loading ...
Sorry, an error occurred while loading the content.

Functions and loops

Expand Messages
  • Douglas Crockford
    JSLint will now providing a warning for code like this: function foo(a) { var i; for (i = 0; i
    Message 1 of 3 , May 6 2:10 PM
    • 0 Attachment
      JSLint will now providing a warning for code like this:

      function foo(a) {
      var i;
      for (i = 0; i < a.length; i += 1) {
      a[i].onclick = function (e) {
      alert(i);
      };
      }
      }

      If you are creating function values inside of a loop, you should make
      them in a closure.

      function foo(a) {
      var i;
      for (i = 0; i < a.length; i += 1) {
      a[i].onclick = function (i) {
      return function (e) {
      alert(i);
      };
      }(i);
      }
      }
    • Alan Green
      Hi Although this is really a javascript (not jslint) issue, could you explain why one should make the function valus in a closure. Thanks Alan ... make
      Message 2 of 3 , May 10 9:12 PM
      • 0 Attachment
        Hi
        Although this is really a javascript (not jslint) issue, could you
        explain why one should make the function valus in a closure.
        Thanks
        Alan

        --- In jslint_com@yahoogroups.com, "Douglas Crockford" <douglas@...>
        wrote:
        >
        > JSLint will now providing a warning for code like this:
        >
        > function foo(a) {
        > var i;
        > for (i = 0; i < a.length; i += 1) {
        > a[i].onclick = function (e) {
        > alert(i);
        > };
        > }
        > }
        >
        > If you are creating function values inside of a loop, you should
        make
        > them in a closure.
        >
        > function foo(a) {
        > var i;
        > for (i = 0; i < a.length; i += 1) {
        > a[i].onclick = function (i) {
        > return function (e) {
        > alert(i);
        > };
        > }(i);
        > }
        > }
        >
      • Douglas Crockford
        ... The common failure case was shown in the example, attaching event handlers in a loop. If the event handlers are bound to variables that are mutated by the
        Message 3 of 3 , May 11 6:10 AM
        • 0 Attachment
          --- In jslint_com@yahoogroups.com, "Alan Green" <alan.green.mail@...>
          wrote:
          >
          > Hi
          > Although this is really a javascript (not jslint) issue, could you
          > explain why one should make the function valus in a closure.
          > Thanks
          > Alan

          The common failure case was shown in the example, attaching event
          handlers in a loop. If the event handlers are bound to variables that
          are mutated by the loop, then they are likely to work incorrectly.
        Your message has been successfully submitted and would be delivered to recipients shortly.