在JavaScript闭包中更改全局变量 [英] Change global variable inside JavaScript closure

查看:316
本文介绍了在JavaScript闭包中更改全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更改闭包中变量的值:

I'm trying to change the value of a variable in a closure:

var myVariable;
$.ajax({
    //stuff....
    success:function(data) {
        myVariable = data;
    }
});

这不起作用,因为 myVariable 可见到闭合。如何更改此代码以使 myVariable 的值更改?

This does not work because myVariable is not visible to the closure. How do I change this code so that the value of myVariable changes?

推荐答案

p>与你的信念相反,你的代码工作。但是看到你想要做什么,并在行之间读取我猜你试图这样做:

Contrary to your belief, your code works. But seeing what you're trying to do and reading between the lines I'm guessing you're trying to do this:

var myVariable;
$.ajax({
    //stuff....
    success:function(data) {
        myVariable = data;
    }
});
alert(myVariable); // at this point myVariable is undefined!!

如果是这样,您需要了解异步函数。

If so, you need to learn about asynchronous functions.

基本上, $。ajax()函数在实际提交ajax请求之前返回。它将在稍后当浏览器不忙于执行javascript时执行ajax请求。这意味着,当您尝试提醒 myVariable 的价值时,该作业将不会发生。

Basically, the $.ajax() function returns before actually submitting the ajax request. It will do the ajax request later when the browser is not busy executing javascript. Which means that the assignment will not have happened yet when you try to alert the value of myVariable.

阅读我的在此处回答更多详情: JS全局变量not在第一次迭代时设置

Read my response here for more detail: JS global variable not being set on first iteration

唯一好的解决方案是改变你对编码的看法。 (有一个可疑的解决方案,涉及将ajax调用同步但不允许,你可以谷歌它,如果你想要或阅读手册)。而不是这样做:

The only good solution is to change the way you think about coding. (There is an arguably bad solution that involves turning the ajax call to synchronous but lets not get in to that, you can google it if you want or read the manual). Instead of doing this:

var myVariable;
$.ajax({
    //stuff....
    success:function(data) {
        myVariable = data;
    }
});
/*
 * Do lots of stuff with the returned value
 * of the myVariable variable
 *
 */

您现在需要这样写:

var myVariable;
$.ajax({
    //stuff....
    success:function(data) {
        myVariable = data;
        /*
         * Do lots of stuff with the returned value
         * of the myVariable variable
         *
         */
    }
});

基本上将您在ajax调用后写入的任何和所有代码移动到成功回调中。这需要习惯(从这个问题有多少变种在互联网上存在)。但是一旦你习惯了它,它就会成为第二大自然。

Basically moving any and all code that you would have written after the ajax call into the success callback. This takes getting used to (judging from how many variants of this question exist on the internet). But once you're used to it it becomes second nature.

这种编程风格有一个名字。它被称为:事件驱动编程或继续传递风格事件编程。如果您想了解更多资讯,可以前往各个条款。

There is a name for this style of programming. It is variously known as: "event driven programming" or "continuation-passing style" or "evented programming". You can google the various terms if you want to know more.

这篇关于在JavaScript闭包中更改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆