javascript-function-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJavaScript/TypeScript Function Style
JavaScript/TypeScript 函数风格
This is a strict guideline. Follow these rules exactly.
How to write functions in JavaScript and TypeScript projects.
这是一项严格的规范,请严格遵守以下规则。
本指南介绍了如何在JavaScript和TypeScript项目中编写函数。
Function Declarations vs Arrow Functions
函数声明与箭头函数对比
Use keyword for:
function- Regular function definitions
- Top-level functions
- Named functions that need hoisting
Use arrow functions for:
- Array methods (,
.map(),.filter()).reduce() - Inline callbacks
- React component props
- When you need lexical binding
this
function- 常规函数定义
- 顶层函数
- 需要变量提升的命名函数
箭头函数适用场景:
- 数组方法(、
.map()、.filter()).reduce() - 行内回调函数
- React组件props
- 需要词法绑定的场景
this
Examples
示例
typescript
// ✅ Regular functions
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
function UserProfile({ userId }: Props) {
return <div>{userId}</div>;
}
// ✅ Arrow functions in appropriate contexts
const numbers = [1, 2, 3].map(n => n * 2);
const handleClick = () => {
console.log('clicked');
};
<Button onClick={() => handleSubmit()} />typescript
// ✅ Regular functions
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
function UserProfile({ userId }: Props) {
return <div>{userId}</div>;
}
// ✅ Arrow functions in appropriate contexts
const numbers = [1, 2, 3].map(n => n * 2);
const handleClick = () => {
console.log('clicked');
};
<Button onClick={() => handleSubmit()} />Why This Pattern
采用该规范的原因
- Consistency: Clear rule makes codebase predictable
- Readability: Function declarations are more explicit
- Flexibility: Arrow functions where they provide value (conciseness, lexical scope)
- 一致性:清晰的规则让代码库风格可预测
- 可读性:函数声明的表意更明确
- 灵活性:在能发挥优势的场景使用箭头函数(写法简洁、自动绑定词法作用域)
Progressive Improvement
持续优化
If the developer corrects a behavior that this skill should have prevented, suggest a specific amendment to this skill to prevent the same correction in the future.
如果开发者修正了本规范本应避免的错误行为,请提出具体的修订建议,避免未来重复出现同类问题。