<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js-块级作用域例外(异常处理)</title>
</head>
<body>
<script>
function test() {
var x = "x", ret = [];
ret.push(x);
/* try {
throw "exception";
} catch(x) { // 注意此处要用 x 捕获,跟之前声明变量的一样,此时x不再是原来的x,而是新的作用域里的捕获的"exception"
alert(x); // exception
x = "catch";
alert(x); // catch
x = x;
alert(x); // catch
}
ret.push(x);
*/
/**
* 个人认为本书中的这里例子-就是上面那个-增加了对这个概念的理解难度,改为如下比较好
*/
try {
throw "exception";
} catch(msg) {
// 是说,这个 msg 的范围是 catch 语句块,在catch块外面是访问不到 msg的
}
// ret.push(msg); // 此处 Uncaught ReferenceError: msg is not defined
return ret;
};
alert(test()); // x,x
</script>
<p>
2. JS 没有块级作用域的一个例外是 异常处理,
try...catch语句将捕获的异常绑定到一个变量,这个变量的作用域只是 catch 语句块。
详见本页举例
<p>
★★★这真是个极其特殊的例子,★★★
在捕获异常的时候要使用声明时的变量,这样在catch里的x其实是捕获的字符串"exception",
不再是原来的"x",
★★★此处也可以充分说明,JS发生异常时,catch时会产生一个新的作用域★★★
</p>
</p>
</body>
</html>