在ECMAScript的5规范规定如下:
通常,词汇环境与ECMAScript代码的某些特定语法结构相关联,例如TryStatement的FunctionDeclaration,WithStatement或Catch子句,并且每次评估此类代码时都会创建新的词法环境.
如果我的理解是正确的,那么当在JavaScript中创建新的词法环境时,会输入一个新的范围,这就是为什么在函数内声明的变量在该函数之外是不可见的:
function example() {
var x = 10;
console.log(x); //10
}
console.log(x); //ReferenceError
Run Code Online (Sandbox Code Playgroud)
因此,在上面的函数声明中,创建了一个新的词法环境,这意味着x在任何可能存在的外部词汇环境中都不可用.
因此,上面关于函数声明的引用部分似乎有意义.但是,它还声明为Try语句的Catch子句创建了一个新的词法环境:
try {
console.log(y); //ReferenceError so we enter catch
}
catch(e) {
var x = 10;
console.log(x); //10
}
console.log(x); //10 - but why is x in scope?
Run Code Online (Sandbox Code Playgroud)
那么catch块的范围如何工作?我是否对词汇环境有什么根本的误解?
当jSLint运行时,javascript 对我大喊大叫,我不知道为什么.
/*jslint browser: true, devel: true, evil: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true */
var foo = function() {
try {
console.log('foo');
} catch(e) {
alert(e);
}
try {
console.log('bar');
} catch(e) {
alert(e);
}
};
foo();
Run Code Online (Sandbox Code Playgroud)
它告诉我:
第12行字符11的问题:'e'已经定义.
} catch(e) {
我有一秒钟似乎很不高兴catch(e).为什么这会成为问题?它不是简单地将e设置为catch块内的局部变量吗?我是否需要为函数中所有陷阱错误唯一命名局部变量?
javascript error-handling exception-handling jslint try-catch