0
function UpgradeShop(){
    var selectedIndex;

    var category_btns = [];
    for(var i = 0; i < 5; i++){
        category_btns[i] = new Button(38, 68 + i * 75, 284, 70);
        category_btns[i].action = function() {
            selectedIndex = i;   // ?
            draw_ui();           // ?
        };
    }

    this.draw_ui = function(){
       ...
    }
}

I have a custom class named Button and I want to create 5 of them. I gave them each an action variable that executes when a click is detected.

The variable selectedIndex as well as the method draw_ui are found in the class that I'm declaring these functions in, not the Button class. I noticed that simply calling draw_ui() cannot be found and this.draw_ui() tries to find the method within the Button class. How do I assert that the function calls and variable assignments get directed towards the defining class?

John
  • 816
  • 5
  • 17
  • 1
    This is a dup of a question that is asked a zillion times about using a `for` loop index value inside an event handler. I'll look up the original now. – jfriend00 Aug 16 '14 at 07:04
  • https://shahpritesh.wordpress.com/2013/09/06/javascript-function-in-loop-passing-dynamic-variable-value/ – Cristi Pufu Aug 16 '14 at 07:04
  • Thank you, that answers one of my questions. However, I'm still looking for an answer on the second. – John Aug 16 '14 at 07:09
  • The second part of your question requires saving `this` in a local variable before your function so you can reference that value to execute `draw_ui()` because `this` will have a different value in the function you assign to `.action`. Put `var self = this;` above the `for` loop and then reference `self.draw_ui()`. – jfriend00 Aug 16 '14 at 07:09
  • 1
    FYI, I reopened the dup because you have multiple questions and only the first part is answered by the dup. – jfriend00 Aug 16 '14 at 07:16

1 Answers1

2

For the first part of your question see this answer: JavaScript closure inside loops – simple practical example as this is a very commonly asked question which has been asked a lot of times (not always easy to find with a search though if you don't know what to search for).

For the second part of your question you need to save the value of this in a local variable like this:

function UpgradeShop(){
    var selectedIndex;

    var category_btns = [];
    var self = this;
    for(var i = 0; i < 5; i++){
        (function(index) {
            category_btns[index] = new Button(38, 68 + i * 75, 284, 70);
            category_btns[index].action = function() {
                selectedIndex = index;
                self.draw_ui();           // use self here
            };
        })(i);
    }

    this.draw_ui = function(){
       ...
    }
}
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    For completeness, I also put the `for` loop closure solution in here, though that part is a dup of the referenced question. – jfriend00 Aug 16 '14 at 07:16