如何从嵌套函数中访问变量

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

本文关键字:访问 变量 函数 嵌套      更新时间:2023-09-28

我需要从嵌套函数中访问一个变量,如下所示:

$(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]);
    });
});

到目前为止,这还没有奏效。当我检查answer的值时,它是未定义的。

这是因为您已经声明了一个名为key的局部变量,因为在单击处理程序中,在var key = randomKey(current_dict);之前使用了var。由于您有一个局部变量,因此不会访问变量外部作用域(闭包)。

$("#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]);
});