"use strict"; v = 1; // 此处报错:Uncaught ReferenceError: v is not defined for(i = 0; i < 2; i++) { // 此处报错:Uncaught ReferenceError: i is not defined }
2.不允许删除变量或函数
1 2 3 4 5 6 7
"use strict"; var person = {name: "Peter", age: 28}; delete person; // 此处报错:Uncaught SyntaxError: Delete of an unqualified identifier in strict mode. functionsum(a, b) { return a + b; } delete sum; // 此处报错:Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.
3.函数中不允许同名的参数
1 2 3 4
"use strict"; functionsquare(a, a) { // 此处报错:Uncaught SyntaxError: Duplicate parameter name not allowed in this context return a * a; }
4.eval语句的作用域是独立的
1 2 3
"use strict"; eval("var x = 5; console.log(x);"); console.log(x); // 此处报错:Uncaught ReferenceError: x is not defined
5.不允许使用with语句
1 2 3 4 5 6 7
"use strict"; var radius1 = 5; var area1 = Math.PI * radius1 * radius1; var radius2 = 5; with(Math) { // 此处报错:Uncaught SyntaxError: Strict mode code may not include a with statement var area2 = PI * radius2 * radius2; }
6.不允许写入只读属性
1 2 3 4
"use strict"; var person = {name: "Peter", age: 28}; Object.defineProperty(person, "gender", {value: "male", writable: false}); person.gender = "female"; // 此处报错:Uncaught TypeError: Cannot assign to read only property 'gender' of object '#<Object>'
7.不允许使用八进制数
1 2 3
"use strict"; var x = 010; // 此处报错:Uncaught SyntaxError: Octal literals are not allowed in strict mode. console.log(parseInt(x));
8.不能在if语句中声明函数
1 2 3 4 5 6 7 8
"use strict"; //如果在if语句中声明函数,则会产生语法错误 if (true) { functiondemo() { // 此处报错:Uncaught ReferenceError: demo is not defined console.log(111); } } demo();
9.禁止使用this表示全局对象
1 2 3 4 5 6
"use strict"; var name = "name"; functiondemoTest() { console.log(this); } demoTest();