为什么“use strict”(JavaScript)不能检测出未声明的变量?

8

我试图让"use strict";指令起作用,但有点困难。在下面的文件中,FireFox 9将(正确地)检测到第3行未声明someVar,但未能检测到第19行未声明theVar。我对为什么会这样感到困惑。

"use strict"; // this will cause the browser to check for errors more aggresively

someVar = 10; // this DOES get caught // LINE 3

// debugger; // this will cause FireBug to open at the bottom of the page/window
        // it will also cause the debugger to stop at this line

    // Yep, using jQuery & anonymous functions
$(document).ready( function(){  
    alert("document is done loading, but not (necessarily) the images!");  

    $("#btnToClick").click( function () {

        alert("About to stop");
        var aVariable = 1;
        debugger; // stop here!
        alert("post stop " + aVariable );

        // this lacks a "var" declaration:
        theVar = 10; // LINE 19  // this is NOT getting caught

        // needs a closing "
        // alert("hi);
        console.log("Program is printing information to help the developer debug a problem!");  
    });

});
2个回答

7

顺便提一下,使用能够通过代码检查器分析您的代码的编辑器将在编辑时捕获这些错误。个人而言,我使用Sublime Text 2,它与SublimeLinter结合使用,可以突出显示JSHint报告的错误。http://www.jshint.com/ - nikc.org
糟糕!我发誓我已经尝试了好几次,但是Firebug没有报错。我回去再试了一次,现在出现了错误,并在Firebug控制台中报告(但只有在点击时)。JSLint在一次通过中报告它(即在调用方法之前不需要等待)。 谢谢! - MikeTheTall
1
你可能需要在回答中指出解析时间和运行时错误报告之间的区别。这是本题的关键概念。 - wewals

1

Javascript在变量作用域方面有点有趣。如果在运行此代码之前运行不同的代码,则可以声明变量,而不会出现任何错误,因此很难在缺少变量时抛出错误,除非在运行时。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接