【问题标题】:Change a variable from outside it's scope [duplicate]从其范围之外更改变量[重复]
【发布时间】:2016-04-15 20:58:59
【问题描述】:
function get_all_channels_by_order(){
    var foobar = false

    mysql_connection.connect()
    mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", function(){
        foobar = true
    })
    mysql_connection.end()
    console.log(foobar)
}

我需要foobar 来返回true,但它却返回false。 这当然是由于 JavaScript 作用域,但我想知道有没有办法克服这个问题?还是不可能?

很抱歉提出这样一个常见问题,但我查看了其他几个 Stack Overflow 问题,但它们没有帮助,我还尝试了很多其他代码而不是这个但没有成功。

【问题讨论】:

    标签: javascript node.js function scope


    【解决方案1】:

    编辑:虽然我的回答是正确的,但显然 OP 的真正问题是他试图在回调返回之前访问一个正在被回调修改的变量。

    试试下面的代码。我创建了一个名为“that”的变量,它存储了对您所在范围的引用。然后,每次我想要正确的 foobar 时,我只需在它前面加上“that”。

    var mysql_connection = {};
    mysql_connection.connect = function(){
       console.log("call to mysql_connection.connect");
    }
    
    mysql_connection.query = function(query,cb){
       console.log("call to mysql_connection.query with query of",query);
       if(cb){
          cb();
       }
    }
    mysql_connection.end = function(){
       console.log("call to mysql_connection.end");
    }
    
    function get_all_channels_by_order(){
        var that = this;
        that.foobar = false;
        console.log("foobar=",that.foobar);
    
        mysql_connection.connect()
        mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", function(){
            that.foobar = true
        })
        mysql_connection.end()
        console.log("foobar=",that.foobar);
    }
    

    【讨论】:

    • 刚试过这个,还是返回false。
    • 然后呢?你的代码仍然打印foobar=false。并且您在查询完成之前关闭连接。
    • 冷静。我假设同步。在写作之前阅读编辑。正如发布的那样,我的代码记录为真。注意我定义了 mysql 方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多