一、JavaScript 严格模式的概念
- JavaScript 严格模式(strict mode)即在严格的条件下运行。
- 使用 “use strict” 指令
- 它不是一条语句,是一个字面量表达式。
- 严格模式下不能使用未声明的变量。
二、JavaScript 严格模式的作用
- 减少js代码的不规范使用和不合理运行,提高运行速度。
三、JavaScript 严格模式的分类
四、JavaScript 严格模式的声明
- 严格模式通过在脚本或函数的头部添加 use strict; 表达式来声明。
五、JavaScript 严格模式的限制
1.不能使用未定义的变量
<script> 'use strict' x = 10; console.log(x); </script>
- 会报错:x is not defined(x未定义)
method(); function method(){ 'use strict' x = 10; console.log(x); } b = 20; console.log(b);
- b没报错,这样就可以很好的区分全局严格和局部严格。
- 因为代码报错,就不会继续往下执行,那么b也就不会输出。
2.不允许删除变量或者对象
'use strict'; var x = 10; console.log(x); delete x;
- 报错:Delete of an unqualified identifier in strict mode.(在严格模式下删除非限定标识符)
3.不允许删除函数
'use strict'; function fun(){ } delete fun;
- 报错:Delete of an unqualified identifier in strict mode.(在严格模式下删除非限定标识符)
4.不允许变量重名
- 仅限于函数的形参不能重名
'use strict'; var a = 10; var a = 20; console.log(a);
'use strict'; fun(); function fun(a,a){ }
- 会报错:Duplicate parameter name not allowed in this context(此上下文中不允许重复的参数名)
5.不允许使用八进制
'use strict'; var x = 010; console.log(x);
- 会报错:Octal literals are not allowed in strict mode(严格模式下不允许使用八进制文字)
6.不允许使用转义字符\
'use strict'; var a = \0102; console.log(a);
- 会报错:Invalid or unexpected token(无效或意外标记)
7.不允许修改只读属性的值
'use strict'; var obj = {}; Object.defineProperty(obj,'x',{ value:10, writable:false//修改writable为false(只读) }); obj.x = 20; console.log(obj.x);
- 会报错:Cannot assign to read only property ‘x’ of object(不能赋值给对象的只读属性“x”)
8.不允许对只有getter方法的属性修改(类似不允许修改只读)
'use strict'; var obj = { get x(){ return 10; } } obj.x = 20; console.log(obj.x);
- 会报错: Cannot set property x of # which has only a getter(不能设置只有getter的属性x)
9.不允许删除对象的原型对象
'use strict'; delete Object.prototype;
- 会报错:Cannot delete property ‘prototype’ of function Object()(不能删除函数对象的原型对象)
10.不能使用eval作为变量名
'use strict'; var eval = 31;
- 会报错: Unexpected eval or arguments in strict mode(严格模式下不能使用eval或者arguments)
11.不能使用arguments作为变量名
'use strict'; var arguments = 10;
- 会报错: Unexpected eval or arguments in strict mode(严格模式下不能使用eval或者arguments)
12.禁止this关键字指向全局对象。
- 非严格模式下:this指针指向window
fun(); function fun(){ console.log(this); }
- 严格模式下:this === undefined,"!this"为true。
'use strict'; fun(); function fun(){ console.log(this); }
'use strict'; fun(); function fun(){ console.log(!this); }