为什么“use strict”(JavaScript)没有检测到未声明的变量?

时间:2011-12-25 16:56:31

标签: javascript jquery strict use-strict

我正在努力获得“严格使用”;工作的指示,并有一点麻烦。在下面的文件中,FireFox 9将(正确地)检测到someVar尚未在第3行声明,但未能检测到第17行尚未声明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 个答案:

答案 0 :(得分:7)

您需要在抛出错误之前调用处理程序。换句话说,请点击#btnToClick

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

答案 1 :(得分:1)

Javascript在变量范围方面有点好笑。如果在运行此代码之前运行不同的代码,则可以声明变量,并且不会出现任何错误,因此除了在运行时之外,很难为丢失的变量抛出错误。