JS 严格模式的核心机制是什么?
- 如何开启
'use strict' // 全局开启 function fn() { 'use strict' // 某个函数开启 } - 特点
- 全局变量必须先声明
"use strict"; n = 10; // ReferenceError: n is not defined - 静止使用 with
"use strict"; var obj = { x: 10 }; with (obj) { // Uncaught SyntaxError: Strict mode code may not include a with statement console.log(x); } - 创建 evel 作用域
"use strict"; var x = 10; eval("var x = 20; console.log(x)"); console.log(x); - 静止 this 指向 window
"use strict"; function fn() { console.log("this", this); // undefined } fn(); - 函数参数不能重名
"use strict"; // Uncaught SyntaxError: Duplicate parameter name not allowed in this context function fn(x, x, y) { return; }
- 全局变量必须先声明