try……catch……
<script type = "text/javascript">
try{
//正在执行的代码,如果出错会终止执行,转到执行catch中的代码
console.log('a');
console.log(b);
console.log('c');
}catch(e){
// e 代表捕捉到的错误对象Error,名称可随意起 如err、error等,它有 name 和 message 属性。
//只有try中的代码出现错误时,才跳进catch中执行。没出现错误catch中的代码不会执行。
console.log(e.name + " : " + e.message);
}
console.log('d');
</script>
错误对象Error的 name 属性对应六种信息:
- EvalError:eval()的使用与定义不一致
- RangeError:数值越界
- ReferenceError:非法或不能识别的引用数值
- SyntaxError:发生语法解析错误
- TypeError:操作数类型错误
- URIError:URI处理函数使用不当
ES5 严格模式
浏览器解释方法的时候 一般规则是基于ES3的方法和ES5的新增方法,如果ES3和ES5有相同的方法时,默认使用ES3的方法。
如果需要使用ES5的方法时,则需要启用 ES5 严格模式。
启用 ES5 严格模式
在全局代码最上端写 "use strict",代表所有代码遵循 ES5 严格模式,或在函数内部第一行写 "use strict",函数内部遵循 ES5 严格模式。
严格模式不在支持 with、arguments.callee、func.caller、常量赋值前必须声明、局部this
必须被赋值(call,unll,undefined都可以)、不允许重复属性和参数。
with 和 eval 举例
<script type = "text/javascript">
var org ={
department_one:{
zhangsan:{
name:"abc",
age:123
}
},
department_two:{
lisi:{
name:"efg",
age:345
}
}
}
var zs = org.department_one.zhangsan;
var ls = org.department_two.lisi;
console.log(zs.name);
console.log(ls.name);
//使用 with 操作命名空间中的变量。
with(org.department_one.zhangsan){
console.log(name);
}
with(org.department_two.lisi){
console.log(name);
}
//使用 eval 执行代码。
eval("x=10;y=20;document.write(x*y)");
var ev = eval("2+2");
console.log(ev);
document.write(eval("2+2"));
var x=10;
document.write(eval(x+17));
</script>