我已经为此担心了一段时间,但我无法意识到真正发生了什么。代码注释中的解释。一个应用程序有 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

最佳答案

很酷,你发现了 hoisting 。 MDN 解释得和任何人一样好:



下面来自 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/

10-12 12:21
查看更多