2011-12-25 50 views
7

我试图得到“严格使用”;指示工作,并有一些麻烦。在以下文件中,FireFox 9将(正确)检测到第3行中没有声明someVar,但未能检测到第19行中没有声明该变量。我很难理解为什么会出现这种情况。为什么不使用“严格”(JavaScript)检测未声明的变量?

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

}); 

回答

7

您需要在引发错误之前调用处理函数。换句话说,请点击#btnToClick

例拨弄:http://jsfiddle.net/X3TQb/

+0

作为一个旁注,使用能够通过linter分析代码的编辑器将捕获这些错误编辑时间。就我个人而言,我使用Sublime Text 2与SublimeLinter结合强调JSHint报告的错误http://www.jshint.com/ – 2011-12-25 17:09:00

+0

坚果!我发誓我实际上已经尝试了几次,并没有从Firebug得到任何错误。 我回去了&再试一次,现在我做的错误是在Firebug控制台中报告(但只有当点击)。 JSLint在一次通过中报告它(即,不等待该方法被调用)。 谢谢! – MikeTheTall 2011-12-26 05:23:58

+1

您可能会指出答案中解析时间和运行时错误报告之间的差异。这是在这里玩的关键概念。 – wewals 2012-10-30 04:19:00

1

JavaScript是有点滑稽,当涉及到可变范围。如果在运行此代码之前运行不同的代码,则可以声明变量,并且不会出现任何错误,因此除运行时外,很难为缺少的变量抛出错误。