Change a variable from outside it's scope [duplicate]

a 夏天 提交于 2019-12-12 04:30:54

问题


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)
}

I need foobar to return true but instead it returns false. This is due of course to the JavaScript scopes, but I was wondering is there any way to overcome this? Or is it impossible?

I am sorry to ask such a common question, but I have looked at several other Stack Overflow questions and they have not helped, I also tried lots of other code rather than this but no successes.


回答1:


EDIT: While my answer holds true, apparently the OP's real issue was that he was trying to access a variable that was being modified by a callback, before the callback returned.

Try the code below. I created a variable called 'that', which stores a reference to the scope you're in. Then, everytime I want the correct foobar, I just prefix it with "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);
}


来源:https://stackoverflow.com/questions/36656716/change-a-variable-from-outside-its-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!