1. 代码风格规范

1.1 缩进与空格

1.2 换行

const result = someVeryLongFunctionName(argument1, argument2, argument3)
  .then(data => {
    // 处理数据
  })
  .catch(error => {
    // 处理错误
  });

1.3 命名规范

const MAX_COUNT = 100;

function getUserInfo(userId) {
  // 逻辑
}

class UserModel {
  constructor() {
    this._privateProperty = 'private';
  }

  _privateMethod() {
    // 私有方法
  }
}

1.4 引号

const name = 'John';
const message = "He's a developer";

1.5 分号

const a = 1;
const b = 2;

1.6 花括号

if (condition) {
  doSomething();
}

1.7 注释

/ 单行注释

/*
 * 多行注释
 */

/**
 * 获取用户信息
 * @param {string} userId - 用户 ID
 * @returns {Object} 用户信息
 */
function getUserInfo(userId) {
  // 逻辑
}

2. 变量与常量

2.1 变量声明


const MAX_COUNT = 100;
let userName = 'John';

2.2 变量初始化

let count = 0;
const name = 'John';

2.3 避免全局变量

3. 函数规范

3.1 函数命名

function calculateTotalPrice(items) {
  // 逻辑
}

3.2 函数参数

function createUser({ name, age, email, address }) {
  // 逻辑
}

3.3 箭头函数

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);

3.4 默认参数

function greet(name = 'Guest') {
  console.log(`Hello, ${name}`);
}

4. 对象与数组

4.1 对象字面量

const user = {
  name: 'John',
  age: 30,
};

4.2 对象属性

const key = 'name';
const user = {
  [key]: 'John',
};

4.3 数组字面量

const numbers = [1, 2, 3];

4.4 数组方法

const doubled = numbers.map(num => num * 2);

5. 类与模块

5.1 类定义

class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}`);
  }
}

5.2 模块化

// user.js
export class User {
  // 类定义
}

// main.js
import { User } from './user.js';

6. 异步编程

6.1 Promise

function fetchData() {
  return new Promise((resolve, reject) => {
    // 异步操作
  });
}

6.2 Async/Await

async function getUser() {
  try {
    const user = await fetchData();
    console.log(user);
  } catch (error) {
    console.error(error);
  }
}

7. 错误处理

7.1 Try/Catch

try {
  doSomething();
} catch (error) {
  console.error(error);
}

7.2 Promise 错误处理

fetchData()
  .then(data => {
    // 处理数据
  })
  .catch(error => {
    console.error(error);
  });