javascript - 在 ajax 请求中使用 "var"关键字时非常奇怪的行为

标签 javascript ajax variables var

我已经为此担心了一段时间,但我无法意识到到底发生了什么。代码注释中的解释。一个应用程序有 2 个版本,其中一个会抛出奇怪的结果,而第二个会执行预期的工作。

var id = "test1";

$.post("http://fiddle.jshell.net/echo/json/", {"data": "data"}, function(a) {
     alert(id); // will throw undefined

     var id = "test2";
     alert(id); // will throw "test2" as expected
});

$.post("http://fiddle.jshell.net/echo/json/", {"data": "data"}, function(a) {
    alert(id); // will throw "test1" as expected

    id = "test2";
    alert(id); // will throw "test2" as expected
});

我不确定它是否与 ajax 调用或匿名函数有关,但这正是我发现它的方式,因此我最好将其保留在那里。有人可以解释我错过了什么吗?为什么当我省略 var 关键字时它的行为会有所不同?你可以尝试一切here on jsFiddle

最佳答案

很酷,您发现了提升。 MDN 对它的解释和任何人一样好:

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

来自以下 MDN 链接的代码示例:

bla = 2
var bla;
// ...

// is implicitly understood as:

var bla;
bla = 2;

您可以看到这将如何导致“奇怪的行为”:

alert(testId);
var testId = 2;

相当于:

var testId;
alert(testId);
testId = 2;

这让我想到了我可以传授的最后一点知识,始终在您的代码块的顶部声明您的变量,以便将这种“奇怪的行为”编码到您的程序中(并且永远不会抛出您再次关闭):

function someFunction() {
   var
    firstVar,
    secondVar,
    thirdVar;

    //rest of your code statements here
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

关于javascript - 在 ajax 请求中使用 "var"关键字时非常奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835236/

相关文章:

java - 设置 JAVA_HOME 与 JRE_HOME 与 PATH 环境变量

javascript - 如何将可写缓冲区通过管道传输到 ReadStream?

javascript - 来自 jquery 插件的 angularjs 指令

python - 基于 Django 类的 DetailView/ListView ajax 装饰器?

ajax - Angular 2 HTTP 进度条

unit-testing - 测试驱动开发 : Writing tests for private/protected variables

javascript - iOS 通过 Javascript 触摸设备的视口(viewport) x/y 坐标

javascript - 如何在 React Native ios 中从 api 添加列表到下拉列表?

jquery - Phalcon getJsonRawBody 无法处理 GET 请求

C++ 比较和递减变量