简体   繁体   中英

Anonymous functions, scope and variables

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?

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(){
       ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM