1.启用严格模式的指令:"use strict"或'use strict',即单引号或双引号均可,也许use将来会成为关键字。
2."use strict"; 以分号结尾,在不支持严格模式的浏览器中(如IE9及以下)被当作一般语句。
3.必须作为全局或函数的首条语句才起到严格模式指令的作用,否则即是一条普通语句。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>use strict</title>
<script>
;//严格模式指令必须在首行,如果之前有语句,它将被当作一个普通字符串,而不是启用严格模式的指令。
"use strict";//全局位置的指令将覆盖到以下定义的所有函数内部
try{
document.writeln("-----start-----<br/>");
k=10;//严格模式下,不用var定义变量是非法的,此句将导致错误,会被catch捕获。
document.writeln("k="+k+"<br/>");
(function(){
"use strict";//局部位置的指令仅仅在本函数内生效。注意:要使该指令在本函数内起作用,必须作为本函数首条语句。
x=100;//严格模式下,不用var定义变量是非法的,此句将导致错误,会被catch捕获。
document.writeln("x="+x+"<br/>");
})();
document.writeln("-----前面没有异常-----<br/>");//如果前面有异常则此句会被忽略
}
catch(e){
document.writeln("错误原因:"+e.name+"<br/>");
document.writeln("错误描述:"+e.message+"<br/>");
}
finally{
document.writeln("-----end-----<br/>");
}
</script>
</head>
<body>
</body>
</html>
严格模式特点:
1.禁止使用with语句
2.变量必须显式定义才可赋值
3.调用函数中的this值是undefined(非严格模式中是全局对象)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>trycatch</title>
<script>
try{
function f1(){
'use strict';
document.writeln("严格模式中的this="+this+"<br/>");
}
function f2(){
document.writeln("非严格模式中的this="+this+"<br/>");
}
f1(); f2();
document.writeln("-----前面没有异常-----<br/>");//如果前面有异常则此句会被忽略
}
catch(e){
document.writeln("错误原因:"+e.name+"<br/>");
document.writeln("错误描述:"+e.message+"<br/>");
}
finally{
}
</script>
</head>
<body>
</body>
</html>
4.
5.关于对象成员扩展
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
</html>
<script>
(function(){
'use strict';
try{
var stu1={"name":"张三","height":"180"};
Object.preventExtensions(stu1);
stu1.weight=75;//严格模式下,对不可扩展的对象创建新成员,会抛出异常
document.writeln(stu1.name+'<br/>');
document.writeln(stu1.weight+'<br/>');
}
catch(e){
document.writeln('错误原由:'+e.name+'<br/>');
document.writeln('错误描述:'+e.message+'<br/>');
}
})();
(function(){
//'use strict';
try{
var stu2={"name":"李四","height":"185"};
Object.preventExtensions(stu2);
stu2.weight=80;//非严格模式下,对不可扩展的对象创建新成员,不会抛出异常(但也不会创建成功)
document.writeln(stu2.name+'<br/>');
document.writeln(stu2.weight+'<br/>');//输出为undefined
}
catch(e){
document.writeln('错误原由:'+e.name+'<br/>');
document.writeln('错误描述:'+e.message+'<br/>');
}
})();
(function(){
//'use strict';
try{
var stu3={"name":"王五","height":"185"};
//Object.preventExtensions(stu3);
stu3.weight=66;//非严格模式下,对象可灵活地扩展新成员
document.writeln(stu3.name+'<br/>');
document.writeln(stu3.weight+'<br/>');
}
catch(e){
document.writeln('错误原由:'+e.name+'<br/>');
document.writeln('错误描述:'+e.message+'<br/>');//输出为66
}
})();
</script>