【问题标题】:Why doesn't "use strict" (JavaScript) detect an undeclared variable?为什么“使用严格”(JavaScript)不检测未声明的变量?
【发布时间】:2012-01-27 16:02:47
【问题描述】:

我正在尝试“使用严格”;指示工作,并有一点麻烦。在以下文件中,FireFox 9 将(正确地)检测到 someVar 尚未在第 3 行声明,但未能检测到 theVar 尚未在第 19 行声明。我很难理解为什么会这样。

"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!");  
    });

});

【问题讨论】:

    标签: javascript jquery strict use-strict


    【解决方案1】:

    当涉及到变量作用域时,Javascript 有点有趣。如果您要在运行此代码之前运行不同的代码,则可以声明变量,并且不会出现任何错误,因此除了在运行时之外,很难为缺少的变量抛出错误。

    【讨论】:

      【解决方案2】:

      您需要在抛出错误之前调用处理程序。也就是说,点击#btnToClick

      小提琴示例:http://jsfiddle.net/X3TQb/

      【讨论】:

      • 作为旁注,使用能够通过 linter 分析代码的编辑器将在编辑时捕获这些错误。就个人而言,我使用 Sublime Text 2 结合 SublimeLinter 突出显示 JSHint jshint.com 报告的错误
      • 疯了!我发誓我实际上尝试了几次,并且根本没有从 Firebug 那里得到任何错误。我回去并再次尝试,现在我确实在 Firebug 控制台中报告了错误(但仅在单击时)。 JSLint 确实会一次性报告它(即,无需等待方法被调用)。谢谢!
      • 您可能会在答案中指出解析时间和运行时错误报告之间的区别。这就是这里的关键概念。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      相关资源
      最近更新 更多