简体   繁体   English

Javascript范围变量(全局/本地)

[英]Javascript scope variable (global/local)

I want to use a local variable as a global variable and I was told the way to do so is to create the variable outside the function, like this: 我想使用局部变量作为全局变量,我被告知这样做的方法是在函数外创建变量,如下所示:

        var foo = null;

        function bar() {
            foo = 3;
        }

        console.log(foo);

However the foo logs null, instead of 3. This is the simplest example I could think of, but mainly I want to be able to use the data from a variable I created in a function throughout my whole script. 然而,foo记录为null,而不是3.这是我能想到的最简单的例子,但主要是我希望能够在整个脚本中使用我在函数中创建的变量中的数据。

What am I doing wrong? 我究竟做错了什么?


Same question in an Ajax request : Ajax请求中的相同问题:

var status = null;

.ajax({
  url: myUrl, 
  success: function (data) {
    status = data.status; //returns a string
    console.log(status); // it works, I get the string
  }, 
  dataType: 'jsonp' 
});

console.log(status); // still null

You need to call the function first like this. 你需要先调用这个函数。

    var foo = null;

    function bar() {
        foo = 3;
    }

    bar();
    console.log(foo);

Your best bet here is to call a function that logs the data after the ajax runs. 这里最好的办法是调用一个在ajax运行后记录数据的函数。 In this example I created a function called logit() which is called in the ajax request state. 在这个例子中,我创建了一个名为logit()的函数,该函数在ajax请求状态中调用。

var status = null;

$.ajax({
  url: myUrl, 
  success: function (data) {
    status = data.status; //returns a string
    console.log(status); // it works, I get the string
    logit();
  }, 
  dataType: 'jsonp' 
});

function logit(){
    console.log("logit(): " + status);
}

The reason you are getting null is because this is the order that your code is running: 获得null的原因是因为这是您的代码运行的顺序:

  1. sets status to null status设置为null
  2. saves the ajax to memory to run when the requests completes this doesn't actually run yet 将ajax保存到内存以在请求完成时运行,但实际上还没有运行
  3. logs status which is still null because the success callback hasn't run yet 记录status仍为null因为成功回调尚未运行
  4. the ajax request finally completes and runs the success callback ajax请求最终完成并运行成功回调
  5. status is set to data.status status设置为data.status

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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