上一篇在说this关键字指向问题时, 一直提到严格模式,这里就和大家浅谈一下什么是严格模式叭~~~
什么是严格模式?
JavaScript 严格模式(strict mode)即指定代码在严格的条件下运行
使用”use strict“指令( JavaScript 1.8.5 (ECMAScript5) 中新增 )它不是一条语句,但是是一个字面量表达式
设立严格模式的目的?
消除Javascript语法的不合理、不严谨之处,减少怪异行为
消除代码运行的不安全之处,保证代码运行的安全
提高编译器效率,增加运行速度
为未来新版本的Javascript做好铺垫
严格模式的限制
禁止使用with语句
禁止this关键字指向全局对象
不允许使用未声明的变量,对象(对象也是一个变量)
不允许删除变量,对象,函数 (delete x 会报错)
不允许变量重名, 对象不能有重名的属性
不允许使用八进制,不允许使用转义字符
不允许对只读属性赋值, 不允许对一个使用getter方法读取的属性进行赋值
不允许删除一个不允许删除的属性
变量名不能使用 "eval","arguments" 字符串
由于一些安全原因,在作用域 eval() 创建的变量不能被调用
使用:
"use strict" 指令只允许出现在脚本或函数的开头
// "use strict" 指令只允许出现在脚本或函数的开头
"use strict"
/* function fn(){
"use strict"
......
} */
// 1. 不允许使用with语句
// with (Math){x = cos(2)} //Uncaught SyntaxError: Strict mode code may not include a with statement
// 2. 禁止this关键字指向全局对象
function fn(){
console.log(this);
}
fn() // undefined
// 使用构造函数时,如果忘了加new,this不再指向全局对象,而是报错
function fun(){
this.a = 1
}
// fun() //Cannot set properties of undefined (setting 'a')
const a = new fun()
console.log(a); // fun {a: 1}
// 3. 不允许使用未声明的变量 对象也是一个变量
// pi = 3.14 // Uncaught ReferenceError: pi is not defined
// x = {p1:10, p2:20} //05-严格模式.js:8 Uncaught ReferenceError: pi is not defined
// 4. 不允许删除变量, 对象, 函数
/* var x = 1
function y(a){}
delete x
delete y */ //Uncaught SyntaxError: Delete of an unqualified identifier in strict mode
// 5. 不允许变量重名
// function q(a,a){} //Uncaught SyntaxError: Duplicate parameter name not allowed in this context
// 6. 不允许使用八进制
// var x = 010; //Uncaught SyntaxError: Octal literals are not allowed in strict mode
// 7. 不允许对只读属性赋值
/* var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false})
obj.x = 1 //Uncaught TypeError: Cannot assign to read only property 'x' of object '#<Object>' */
// 8. 不允许对一个使用getter方法读取的属性进行赋值
/* var obj = {get x() {return 0} };
obj.x = 3.14; //05-严格模式.js:30 Uncaught TypeError: Cannot set property x of #<Object> which has only a getter */
// 9. 不允许删除一个不允许删除的属性
// delete Object.prototype //05-严格模式.js:33 Uncaught TypeError: Cannot delete property 'prototype' of function Object() { [native code] }
// 10. 变量名不能使用 "eval", "arguments" 字符串
// var eval = 3.14
// var arguments = 3.14
//Uncaught SyntaxError: Unexpected eval or arguments in strict mode
// 11.由于一些安全原因,在作用域 eval() 创建的变量不能被调用
// eval ("var x = 2");
// alert (x); //Uncaught ReferenceError: x is not defined