0
<body>
    <div id="links">

    </div>
</body>

<script type="text/javascript">
    var A = function(j) {
        this.b = j;
    };
    var links = $("#links");
    for (var i = 0; i < 100; i++) {
        var a = new A(i);    // a is the local variable mentioned in the question
        links.append($("<a> " + i + " </a>").click(function() {
            console.log(a.b);  
                 // when the <a>i</a> is clicked 99 is always printed to console
        }));
    }
</script>

In this above script when, say, <a>45</a> is clicked, i thought 45 will be printed, but instead 99 is printed. No matter what link is clicked, 99 is always printed. I thought a being accessed inside console.log() will point to the local a that was created in that particular loop, and so would print the corresponding value of i. Why is this happening? Am I doing something wrong?

Anyway, now I need it such that when the links are clicked, their corresponding objects are acted upon, not the object that was created last. How will I achieve this?

TK Omble
  • 369
  • 3
  • 8
  • For how closures work, see the linked duplicate. For how to get from click handler to click target, as an alternative to a closure, the handler will receive the click event and/or target object as an argument, so you can go from there. – Thilo Jun 04 '14 at 05:09

1 Answers1

0

Demo

try

     var A = function (j) {
      this.b = j;
  };
  var links = $("#links");
  for (var i = 0; i < 100; i++) {

      (function () {
          var a = new A(i); // a is the local variable mentioned in the question
          links.append($("<a> " + i + " </a>").click(function () {
              console.log(a.b);

          }));
      })(i);
  }
Balachandran
  • 9,567
  • 1
  • 16
  • 26