严格模式的限制

JavaScript use strict 模式下的语法限制和行为变化

问题

JavaScript 中 "use strict" 严格模式有哪些限制?

解答

严格模式通过在脚本或函数开头添加 "use strict" 启用,它消除了一些不安全的语法,让代码更规范。

1. 变量必须声明

"use strict";

x = 10; // ReferenceError: x is not defined

// 正确写法
let x = 10;

2. 禁止删除变量和函数

"use strict";

let x = 10;
delete x; // SyntaxError

function foo() {}
delete foo; // SyntaxError

3. 函数参数不能重名

"use strict";

// SyntaxError: Duplicate parameter name not allowed
function sum(a, a, b) {
  return a + a + b;
}

4. 禁止八进制字面量

"use strict";

let num = 010; // SyntaxError

// 正确写法:使用 0o 前缀
let num = 0o10; // 8

5. 禁止使用 with 语句

"use strict";

// SyntaxError
with (Math) {
  let x = cos(PI);
}

6. this 不再默认指向全局对象

"use strict";

function showThis() {
  console.log(this); // undefined,非严格模式下是 window
}

showThis();

7. 禁止对只读属性赋值

"use strict";

const obj = {};
Object.defineProperty(obj, "x", { value: 1, writable: false });

obj.x = 2; // TypeError: Cannot assign to read only property

8. 禁止删除不可配置的属性

"use strict";

delete Object.prototype; // TypeError

9. eval 有独立作用域

"use strict";

eval("var x = 10");
console.log(x); // ReferenceError: x is not defined

// 非严格模式下 x 会泄漏到外部作用域

10. arguments 不追踪参数变化

"use strict";

function test(a) {
  a = 100;
  console.log(arguments[0]); // 1,不会变成 100
}

test(1);

// 非严格模式下 arguments[0] 会变成 100

11. 保留字不能作为变量名

"use strict";

// SyntaxError
let implements = 1;
let interface = 2;
let private = 3;
let public = 4;

关键点

  • 变量必须先声明再使用,防止意外创建全局变量
  • 函数内 thisundefined,不再默认绑定全局对象
  • eval 有独立作用域,不会污染外部环境
  • arguments 与参数解绑,修改参数不影响 arguments
  • 禁止八进制字面量、with 语句、重复参数名等不安全语法