JavaScript 严格模式

定义

严格模式(Strict Mode)是ES5引入的一种限制性JavaScript执行模式,旨在消除语言中不合理、不安全、不明确的部分,提供更好的错误检查机制。

启用方式

全局严格模式

"use strict";  // 整个脚本使用严格模式
 
let userName = "John";
function greet() {
    console.log("Hello, " + userName);
}

函数级严格模式

function strictFunction() {
    "use strict";  // 仅此函数使用严格模式
    
    let localVar = "test";
    // 严格模式规则仅在此函数内生效
}

模块默认严格模式

// ES6模块自动启用严格模式
export function moduleFunction() {
    // 无需声明 "use strict",默认就是严格模式
}

主要限制

变量声明限制

"use strict";
 
// 错误:未声明变量赋值
x = 10;  // ReferenceError
 
// 错误:删除变量
let y = 20;
delete y;  // SyntaxError
 
// 错误:重复参数名
function test(a, a) {  // SyntaxError
    return a;
}

对象属性限制

"use strict";
 
// 错误:删除不可删除的属性
delete Object.prototype;  // TypeError
 
// 错误:给不可写属性赋值
let obj = {};
Object.defineProperty(obj, "prop", {
    value: 1,
    writable: false
});
obj.prop = 2;  // TypeError

this 绑定规则

"use strict";
 
function regularFunction() {
    console.log(this);  // undefined(非严格模式下是全局对象)
}
 
regularFunction();
 
// 对象方法中的this正常工作
let obj = {
    method: function() {
        console.log(this);  // obj
    }
};

八进制字面量限制

"use strict";
 
// 错误:八进制字面量
let num = 077;  // SyntaxError
 
// 正确:使用 0o 前缀
let octal = 0o77;  // 63(十进制)

严格模式的好处

错误捕获

"use strict";
 
// 严格模式会捕获更多潜在错误
function example() {
    // 拼写错误会立即报错
    userName = "John";  // ReferenceError(假设未声明)
}

性能优化

"use strict";
 
// 引擎可以更好地优化严格模式代码
function calculate(a, b) {
    return a + b;  // 更容易进行JIT优化
}

未来兼容性

"use strict";
 
// 保留关键字在严格模式下不能作为标识符
// let interface = "test";  // SyntaxError
// let implements = "test";  // SyntaxError

最佳实践

推荐使用场景

  • 所有新项目:建议默认启用严格模式
  • ES6模块:自动启用,无需手动声明
  • 函数级使用:在需要特殊限制的函数中使用

迁移策略

// 渐进式迁移:先在新函数中使用
function newFeature() {
    "use strict";
    // 新功能代码
}
 
// 逐步将整个文件转换为严格模式

团队开发建议

// 配合ESLint等工具
module.exports = {
    rules: {
        'strict': ['error', 'global']  // 强制使用严格模式
    }
};

兼容性注意事项

浏览器支持

  • 现代浏览器:完全支持
  • 旧版本:IE10+支持
  • 移动端:广泛支持

混合模式处理

// 文件1:严格模式
"use strict";
function strictFunc() { /* ... */ }
 
// 文件2:非严格模式
function normalFunc() { /* ... */ }
 
// 合并后需要注意作用域

第三方库兼容

// 检查库是否支持严格模式
try {
    "use strict";
    // 使用第三方库
} catch (e) {
    // 降级处理
}

常见错误解决

全局变量意外创建

"use strict";
 
// 错误写法
function createUser() {
    userName = "John";  // ReferenceError
}
 
// 正确写法
function createUser() {
    let userName = "John";
    return userName;
}

this 指向问题

"use strict";
 
// 问题代码
function Handler() {
    setTimeout(function() {
        console.log(this);  // undefined
    }, 1000);
}
 
// 解决方案
function Handler() {
    const self = this;
    setTimeout(function() {
        console.log(self);  // Handler实例
    }, 1000);
}

下一篇:语句