✅ 变量声明:let
与 const
的正确使用
- 优先使用
const
除非需要重新赋值 - 避免使用
var
,ES6 已弃用全局作用域提升 - 块级作用域:
let/const
仅在{}
内有效if (true) { const x = 10; // 仅在if块内有效 }
⚡ 箭头函数:简洁且避免 this 混乱
- 单表达式函数简写:
const sum = (a, b) => a + b;
- 无需绑定 this:箭头函数继承外层 this
- 推荐用于回调函数:如数组
.map()
或.sort()
📦 模块化:import
与 export
的规范写法
- 显式导出:
export function greet() { ... }
- 默认导出:
export default class Calculator { ... }
- 按需导入:
import { add, subtract } from './math';
🧠 类与继承:ES6 类语法的现代写法
- 使用
class
定义类,继承通过extends
- 构造函数:
constructor()
必须使用 - 静态方法:用
static
关键字定义static createInstance() { return new this(); }
📌 扩展阅读
⚠️ 注意事项
- 避免滥用
eval
:存在安全风险 - 谨慎使用
with
:可能破坏作用域链 - 保持代码简洁:遵循 JavaScript 开发规范