简体   繁体   中英

How can I access a variable from within a nested function?

I need to access a variable from within a nested function like so:

$(function() {  

    var key = getRandomKey(dictionary);
    resetInputRow(dictionary[key]);

    $("#button").click( function() {
        var answer = key;

        // check if user input matches answer (the original key)
        ...

        // reset key for next check
        var key = randomKey(dictionary);
        resetInputRow(dictionary[key]);
    });
});

So far, this hasn't been working. When I check the value of answer it is undefined.

It is because you have declared a local variable called key , because you have used var before var key = randomKey(current_dict); in the click handler. Since you have a local variable the variable external scope(closure) will not be accessed.

$("#button").click(function () {
    var answer = key;

    // check if user input matches answer (the original key)
    ...

    // reset key for next check
    key = randomKey(dictionary);
    resetInputRow(dictionary[key]);
});

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