目录

React-18.x-学习计划-第二天ES6高级语法

React 18.x 学习计划 - 第二天:ES6高级语法

学习目标

  • 掌握模板字符串和标签模板
  • 理解ES6模块化系统
  • 学会类和继承的使用
  • 掌握Promise和async/await
  • 为React组件开发做准备

学习时间安排

总时长:5-6小时

  • 理论学习:2.5小时
  • 代码实践:2.5-3.5小时

第一部分:模板字符串和标签模板 (1小时)

1.1 模板字符串基础

基本语法
// 传统字符串拼接
const name = 'React';
const version = '18.x';
const message = 'Hello, ' + name + ' version ' + version + '!';

// 模板字符串
const message = `Hello, ${name} version ${version}!`;

// 多行字符串
const multiLine = `
  This is a
  multi-line
  string
`;

// 表达式计算
const a = 10;
const b = 20;
const result = `The sum of ${a} and ${b} is ${a + b}`;
console.log(result); // "The sum of 10 and 20 is 30"
模板字符串的高级用法
// 函数调用
function formatCurrency(amount) {
  return `$${amount.toFixed(2)}`;
}

const price = 99.99;
const displayPrice = `Price: ${formatCurrency(price)}`;
console.log(displayPrice); // "Price: $99.99"

// 条件表达式
const isLoggedIn = true;
const userName = 'John';
const greeting = `Welcome ${isLoggedIn ? userName : 'Guest'}!`;
console.log(greeting); // "Welcome John!"

// 数组和对象
const items = ['apple', 'banana', 'orange'];
const list = `Shopping list: ${items.join(', ')}`;
console.log(list); // "Shopping list: apple, banana, orange"

const user = { name: 'Alice', age: 30 };
const userInfo = `User: ${user.name}, Age: ${user.age}`;
console.log(userInfo); // "User: Alice, Age: 30"

1.2 标签模板

// 基本标签模板
function highlight(strings, ...values) {
  return strings.reduce((result, string, i) => {
    const value = values[i] ? `<mark>${values[i]}</mark>` : '';
    return result + string + value;
  }, '');
}

const name = 'React';
const version = '18.x';
const html = highlight`Welcome to ${name} ${version}!`;
console.log(html); // "Welcome to <mark>React</mark> <mark>18.x</mark>!"

// 安全HTML转义
function escapeHtml(strings, ...values) {
  return strings.reduce((result, string, i) => {
    const value = values[i] ? values[i]
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;') : '';
    return result + string + value;
  }, '');
}

const userInput = '<script>alert("XSS")</script>';
const safeHtml = escapeHtml`User input: ${userInput}`;
console.log(safeHtml); // "User input: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;"

// SQL查询构建器
function sql(strings, ...values) {
  return strings.reduce((query, string, i) => {
    const value = values[i] ? `'${values[i].replace(/'/g, "''")}'` : '';
    return query + string + value;
  }, '');
}

const tableName = 'users';
const condition = "name = 'John'";
const query = sql`SELECT * FROM ${tableName} WHERE ${condition}`;
console.log(query); // "SELECT * FROM 'users' WHERE 'name = ''John'''"

1.3 实际应用示例

// 日志记录器
function log(level, strings, ...values) {
  const timestamp = new Date().toISOString();
  const message = strings.reduce((result, string, i) => {
    return result + string + (values[i] || '');
  }, '');
  
  console.log(`[${timestamp}] [${level.toUpperCase()}] ${message}`);
}

const errorCode = 404;
const resource = 'user';
log`error` `Failed to fetch ${resource} with code ${errorCode}`;

// 国际化支持
const translations = {
  en: {
    welcome: 'Welcome',
    goodbye: 'Goodbye'
  },
  es: {
    welcome: 'Bienvenido',
    goodbye: 'Adiós'
  }
};

function t(language, strings, ...values) {
  const template = strings.reduce((result, string, i) => {
    return result + string + (values[i] || '');
  }, '');
  
  return translations[language][template] || template;
}

const userName = 'Alice';
const welcomeEn = t`en` `welcome` `, ${userName}!`;
const welcomeEs = t`es` `welcome` `, ${userName}!`;
console.log(welcomeEn); // "Welcome, Alice!"
console.log(welcomeEs); // "Bienvenido, Alice!"

第二部分:ES6模块化系统 (1.5小时)

2.1 模块基础

创建模块文件
// math.js - 数学工具模块
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  if (b === 0) {
    throw new Error('Division by zero');
  }
  return a / b;
}

// 默认导出
export default class Calculator {
  constructor() {
    this.history = [];
  }
  
  calculate(operation, a, b) {
    const result = operation(a, b);
    this.history.push({ operation: operation.name, a, b, result });
    return result;
  }
  
  getHistory() {
    return this.history;
  }
}
导入模块
// main.js - 主文件
// 命名导入
import { add, subtract, multiply, divide, PI } from './math.js';

// 默认导入
import Calculator from './math.js';

// 混合导入
import Calculator, { add, subtract } from './math.js';

// 重命名导入
import { add as addition, subtract as subtraction } from './math.js';

// 导入所有
import * as MathUtils from './math.js';

// 使用示例
console.log(add(5, 3)); // 8
console.log(PI); // 3.14159

const calc = new Calculator();
const result = calc.calculate(add, 10, 5);
console.log(result); // 15
console.log(calc.getHistory());

// 使用重命名的函数
console.log(addition(2, 3)); // 5

// 使用命名空间
console.log(MathUtils.multiply(4, 6)); // 24

2.2 高级模块特性

动态导入
// 动态导入函数
async function loadModule(moduleName) {
  try {
    const module = await import(`./modules/${moduleName}.js`);
    return module;
  } catch (error) {
    console.error(`Failed to load module ${moduleName}:`, error);
    return null;
  }
}

// 使用动态导入
async function initializeApp() {
  const mathModule = await loadModule('math');
  const utilsModule = await loadModule('utils');
  
  if (mathModule && utilsModule) {
    console.log('All modules loaded successfully');
    return { math: mathModule, utils: utilsModule };
  }
  
  throw new Error('Failed to load required modules');
}

// 条件导入
async function loadFeature(featureName) {
  if (featureName === 'advanced') {
    const { AdvancedFeatures } = await import('./advanced.js');
    return new AdvancedFeatures();
  } else {
    const { BasicFeatures } = await import('./basic.js');
    return new BasicFeatures();
  }
}
模块重新导出
// utils/index.js - 工具模块入口
export { add, subtract, multiply, divide } from './math.js';
export { formatDate, parseDate } from './date.js';
export { validateEmail, validatePhone } from './validation.js';

// 重新导出默认导出
export { default as Calculator } from './math.js';

// 重命名重新导出
export { add as mathAdd, subtract as mathSubtract } from './math.js';

2.3 模块化项目结构

// 项目结构示例
/*
src/
├── components/
│   ├── Button.js
│   ├── Input.js
│   └── index.js
├── utils/
│   ├── math.js
│   ├── date.js
│   └── index.js
├── services/
│   ├── api.js
│   └── storage.js
└── main.js
*/

// components/Button.js
export class Button {
  constructor(text, onClick) {
    this.text = text;
    this.onClick = onClick;
  }
  
  render() {
    return `<button onclick="${this.onClick}">${this.text}</button>`;
  }
}

// components/Input.js
export class Input {
  constructor(type, placeholder) {
    this.type = type;
    this.placeholder = placeholder;
  }
  
  render() {
    return `<input type="${this.type}" placeholder="${this.placeholder}">`;
  }
}

// components/index.js
export { Button } from './Button.js';
export { Input } from './Input.js';

// 使用组件
import { Button, Input } from './components/index.js';

const button = new Button('Click me', 'handleClick()');
const input = new Input('text', 'Enter your name');

第三部分:类和继承 (1.5小时)

3.1 类的基础语法

// 基本类定义
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  // 实例方法
  greet() {
    return `Hello, I'm ${this.name}`;
  }
  
  // 静态方法
  static createAdult(name) {
    return new Person(name, 18);
  }
  
  // Getter
  get info() {
    return `${this.name} is ${this.age} years old`;
  }
  
  // Setter
  set age(newAge) {
    if (newAge < 0) {
      throw new Error('Age cannot be negative');
    }
    this._age = newAge;
  }
  
  get age() {
    return this._age;
  }
}

// 使用类
const person = new Person('Alice', 25);
console.log(person.greet()); // "Hello, I'm Alice"
console.log(person.info); // "Alice is 25 years old"

const adult = Person.createAdult('Bob');
console.log(adult.age); // 18

3.2 继承和多态

// 基类
class Animal {
  constructor(name, species) {
    this.name = name;
    this.species = species;
  }
  
  speak() {
    return `${this.name} makes a sound`;
  }
  
  move() {
    return `${this.name} moves`;
  }
}

// 子类继承
class Dog extends Animal {
  constructor(name, breed) {
    super(name, 'Canine');
    this.breed = breed;
  }
  
  // 重写父类方法
  speak() {
    return `${this.name} barks`;
  }
  
  // 新增方法
  fetch() {
    return `${this.name} fetches the ball`;
  }
}

class Cat extends Animal {
  constructor(name, color) {
    super(name, 'Feline');
    this.color = color;
  }
  
  speak() {
    return `${this.name} meows`;
  }
  
  purr() {
    return `${this.name} purrs`;
  }
}

// 使用继承
const dog = new Dog('Buddy', 'Golden Retriever');
const cat = new Cat('Whiskers', 'Orange');

console.log(dog.speak()); // "Buddy barks"
console.log(cat.speak()); // "Whiskers meows"
console.log(dog.fetch()); // "Buddy fetches the ball"
console.log(cat.purr()); // "Whiskers purrs"

3.3 抽象类和接口模式

// 抽象基类
class Shape {
  constructor(color) {
    if (this.constructor === Shape) {
      throw new Error('Shape is an abstract class');
    }
    this.color = color;
  }
  
  // 抽象方法(子类必须实现)
  getArea() {
    throw new Error('getArea method must be implemented');
  }
  
  getPerimeter() {
    throw new Error('getPerimeter method must be implemented');
  }
  
  // 具体方法
  getColor() {
    return this.color;
  }
  
  setColor(color) {
    this.color = color;
  }
}

// 具体实现
class Rectangle extends Shape {
  constructor(width, height, color) {
    super(color);
    this.width = width;
    this.height = height;
  }
  
  getArea() {
    return this.width * this.height;
  }
  
  getPerimeter() {
    return 2 * (this.width + this.height);
  }
}

class Circle extends Shape {
  constructor(radius, color) {
    super(color);
    this.radius = radius;
  }
  
  getArea() {
    return Math.PI * this.radius * this.radius;
  }
  
  getPerimeter() {
    return 2 * Math.PI * this.radius;
  }
}

// 使用形状
const rectangle = new Rectangle(10, 5, 'red');
const circle = new Circle(7, 'blue');

console.log(`Rectangle area: ${rectangle.getArea()}`);
console.log(`Circle area: ${circle.getArea()}`);

3.4 混入模式

// 混入对象
const TimestampMixin = {
  getTimestamp() {
    return new Date().toISOString();
  },
  
  getAge() {
    return Date.now() - this.createdAt;
  }
};

const LoggableMixin = {
  log(message) {
    console.log(`[${this.constructor.name}] ${message}`);
  },
  
  error(message) {
    console.error(`[${this.constructor.name}] ERROR: ${message}`);
  }
};

// 应用混入
class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
    this.createdAt = Date.now();
  }
  
  getInfo() {
    return `${this.name} (${this.email})`;
  }
}

// 手动应用混入
Object.assign(User.prototype, TimestampMixin, LoggableMixin);

// 使用混入
const user = new User('John', 'john@example.com');
console.log(user.getInfo());
console.log(user.getTimestamp());
user.log('User created');

第四部分:Promise和异步编程 (1小时)

4.1 Promise基础

// 创建Promise
function fetchUserData(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (userId > 0) {
        resolve({
          id: userId,
          name: 'John Doe',
          email: 'john@example.com'
        });
      } else {
        reject(new Error('Invalid user ID'));
      }
    }, 1000);
  });
}

// 使用Promise
fetchUserData(1)
  .then(user => {
    console.log('User data:', user);
    return user.name;
  })
  .then(name => {
    console.log('User name:', name);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

4.2 async/await语法

// 异步函数
async function getUserData(userId) {
  try {
    const user = await fetchUserData(userId);
    console.log('User data:', user);
    return user;
  } catch (error) {
    console.error('Error:', error.message);
    throw error;
  }
}

// 并行处理
async function getMultipleUsers(userIds) {
  try {
    const promises = userIds.map(id => fetchUserData(id));
    const users = await Promise.all(promises);
    return users;
  } catch (error) {
    console.error('Error fetching users:', error);
    return [];
  }
}

// 使用示例
async function main() {
  try {
    const user = await getUserData(1);
    console.log('Single user:', user);
    
    const users = await getMultipleUsers([1, 2, 3]);
    console.log('Multiple users:', users);
  } catch (error) {
    console.error('Main function error:', error);
  }
}

main();

4.3 高级异步模式

// 超时处理
function withTimeout(promise, timeoutMs) {
  return Promise.race([
    promise,
    new Promise((_, reject) => 
      setTimeout(() => reject(new Error('Timeout')), timeoutMs)
    )
  ]);
}

// 重试机制
async function retry(fn, maxRetries = 3, delay = 1000) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

// 使用重试
async function fetchWithRetry(url) {
  return retry(async () => {
    const response = await fetch(url);
    if (!response.ok) throw new Error('Network error');
    return response.json();
  });
}

// 批量处理
async function processBatch(items, batchSize = 5) {
  const results = [];
  
  for (let i = 0; i < items.length; i += batchSize) {
    const batch = items.slice(i, i + batchSize);
    const batchPromises = batch.map(item => processItem(item));
    const batchResults = await Promise.all(batchPromises);
    results.push(...batchResults);
  }
  
  return results;
}

第五部分:实践项目 (1.5-2小时)

项目:任务管理系统

// Task.js - 任务类
export class Task {
  constructor(title, description, priority = 'medium', dueDate = null) {
    this.id = Date.now() + Math.random();
    this.title = title;
    this.description = description;
    this.priority = priority;
    this.dueDate = dueDate;
    this.completed = false;
    this.createdAt = new Date();
    this.updatedAt = new Date();
  }
  
  complete() {
    this.completed = true;
    this.updatedAt = new Date();
  }
  
  update(updates) {
    Object.assign(this, updates);
    this.updatedAt = new Date();
  }
  
  isOverdue() {
    if (!this.dueDate || this.completed) return false;
    return new Date() > new Date(this.dueDate);
  }
  
  getDaysUntilDue() {
    if (!this.dueDate) return null;
    const now = new Date();
    const due = new Date(this.dueDate);
    const diffTime = due - now;
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }
}

// TaskManager.js - 任务管理器
export class TaskManager {
  constructor() {
    this.tasks = [];
    this.filters = {
      completed: null,
      priority: null,
      overdue: false
    };
  }
  
  addTask(taskData) {
    const task = new Task(
      taskData.title,
      taskData.description,
      taskData.priority,
      taskData.dueDate
    );
    this.tasks.push(task);
    return task;
  }
  
  getTask(id) {
    return this.tasks.find(task => task.id === id);
  }
  
  updateTask(id, updates) {
    const task = this.getTask(id);
    if (task) {
      task.update(updates);
      return task;
    }
    return null;
  }
  
  deleteTask(id) {
    const index = this.tasks.findIndex(task => task.id === id);
    if (index !== -1) {
      return this.tasks.splice(index, 1)[0];
    }
    return null;
  }
  
  completeTask(id) {
    const task = this.getTask(id);
    if (task) {
      task.complete();
      return task;
    }
    return null;
  }
  
  getFilteredTasks() {
    return this.tasks.filter(task => {
      if (this.filters.completed !== null && task.completed !== this.filters.completed) {
        return false;
      }
      if (this.filters.priority && task.priority !== this.filters.priority) {
        return false;
      }
      if (this.filters.overdue && !task.isOverdue()) {
        return false;
      }
      return true;
    });
  }
  
  setFilter(filterType, value) {
    this.filters[filterType] = value;
  }
  
  getStats() {
    const total = this.tasks.length;
    const completed = this.tasks.filter(task => task.completed).length;
    const overdue = this.tasks.filter(task => task.isOverdue()).length;
    const highPriority = this.tasks.filter(task => task.priority === 'high').length;
    
    return {
      total,
      completed,
      pending: total - completed,
      overdue,
      highPriority,
      completionRate: total > 0 ? (completed / total * 100).toFixed(1) : 0
    };
  }
  
  exportTasks() {
    return this.tasks.map(task => ({
      id: task.id,
      title: task.title,
      description: task.description,
      priority: task.priority,
      dueDate: task.dueDate,
      completed: task.completed,
      createdAt: task.createdAt.toISOString(),
      updatedAt: task.updatedAt.toISOString()
    }));
  }
  
  importTasks(tasksData) {
    tasksData.forEach(taskData => {
      const task = new Task(
        taskData.title,
        taskData.description,
        taskData.priority,
        taskData.dueDate
      );
      task.id = taskData.id;
      task.completed = taskData.completed;
      task.createdAt = new Date(taskData.createdAt);
      task.updatedAt = new Date(taskData.updatedAt);
      this.tasks.push(task);
    });
  }
}

// TaskRenderer.js - 任务渲染器
export class TaskRenderer {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.taskManager = new TaskManager();
    this.init();
  }
  
  init() {
    this.render();
    this.bindEvents();
  }
  
  render() {
    const tasks = this.taskManager.getFilteredTasks();
    const stats = this.taskManager.getStats();
    
    this.container.innerHTML = `
      <div class="task-stats">
        <h3>Task Statistics</h3>
        <p>Total: ${stats.total} | Completed: ${stats.completed} | Pending: ${stats.pending}</p>
        <p>Overdue: ${stats.overdue} | High Priority: ${stats.highPriority}</p>
        <p>Completion Rate: ${stats.completionRate}%</p>
      </div>
      
      <div class="task-filters">
        <select id="filter-completed">
          <option value="">All Tasks</option>
          <option value="false">Pending</option>
          <option value="true">Completed</option>
        </select>
        
        <select id="filter-priority">
          <option value="">All Priorities</option>
          <option value="low">Low</option>
          <option value="medium">Medium</option>
          <option value="high">High</option>
        </select>
        
        <label>
          <input type="checkbox" id="filter-overdue"> Overdue Only
        </label>
      </div>
      
      <div class="task-form">
        <input type="text" id="task-title" placeholder="Task title">
        <textarea id="task-description" placeholder="Task description"></textarea>
        <select id="task-priority">
          <option value="low">Low Priority</option>
          <option value="medium" selected>Medium Priority</option>
          <option value="high">High Priority</option>
        </select>
        <input type="date" id="task-due-date">
        <button id="add-task">Add Task</button>
      </div>
      
      <div class="task-list">
        ${tasks.map(task => this.renderTask(task)).join('')}
      </div>
    `;
  }
  
  renderTask(task) {
    const overdueClass = task.isOverdue() ? 'overdue' : '';
    const completedClass = task.completed ? 'completed' : '';
    const priorityClass = `priority-${task.priority}`;
    
    return `
      <div class="task-item ${overdueClass} ${completedClass} ${priorityClass}" data-id="${task.id}">
        <div class="task-header">
          <h4>${task.title}</h4>
          <div class="task-actions">
            <button class="complete-btn" ${task.completed ? 'disabled' : ''}>
              ${task.completed ? 'Completed' : 'Complete'}
            </button>
            <button class="delete-btn">Delete</button>
          </div>
        </div>
        <p class="task-description">${task.description}</p>
        <div class="task-meta">
          <span class="priority">${task.priority.toUpperCase()}</span>
          ${task.dueDate ? `<span class="due-date">Due: ${new Date(task.dueDate).toLocaleDateString()}</span>` : ''}
          ${task.isOverdue() ? '<span class="overdue-badge">OVERDUE</span>' : ''}
        </div>
      </div>
    `;
  }
  
  bindEvents() {
    // 添加任务
    document.getElementById('add-task').addEventListener('click', () => {
      const title = document.getElementById('task-title').value;
      const description = document.getElementById('task-description').value;
      const priority = document.getElementById('task-priority').value;
      const dueDate = document.getElementById('task-due-date').value;
      
      if (title.trim()) {
        this.taskManager.addTask({ title, description, priority, dueDate });
        this.render();
        this.clearForm();
      }
    });
    
    // 完成任务
    this.container.addEventListener('click', (e) => {
      if (e.target.classList.contains('complete-btn')) {
        const taskId = parseFloat(e.target.closest('.task-item').dataset.id);
        this.taskManager.completeTask(taskId);
        this.render();
      }
    });
    
    // 删除任务
    this.container.addEventListener('click', (e) => {
      if (e.target.classList.contains('delete-btn')) {
        const taskId = parseFloat(e.target.closest('.task-item').dataset.id);
        this.taskManager.deleteTask(taskId);
        this.render();
      }
    });
    
    // 过滤器
    document.getElementById('filter-completed').addEventListener('change', (e) => {
      this.taskManager.setFilter('completed', e.target.value === '' ? null : e.target.value === 'true');
      this.render();
    });
    
    document.getElementById('filter-priority').addEventListener('change', (e) => {
      this.taskManager.setFilter('priority', e.target.value || null);
      this.render();
    });
    
    document.getElementById('filter-overdue').addEventListener('change', (e) => {
      this.taskManager.setFilter('overdue', e.target.checked);
      this.render();
    });
  }
  
  clearForm() {
    document.getElementById('task-title').value = '';
    document.getElementById('task-description').value = '';
    document.getElementById('task-priority').value = 'medium';
    document.getElementById('task-due-date').value = '';
  }
}

// main.js - 主文件
import { TaskRenderer } from './TaskRenderer.js';

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
  const app = new TaskRenderer('app');
});

高级练习:异步任务处理

// AsyncTaskProcessor.js - 异步任务处理器
export class AsyncTaskProcessor {
  constructor() {
    this.tasks = [];
    this.processing = false;
    this.processors = [];
  }
  
  addProcessor(processor) {
    this.processors.push(processor);
  }
  
  async addTask(taskData) {
    const task = {
      id: Date.now() + Math.random(),
      ...taskData,
      status: 'pending',
      createdAt: new Date(),
      processedAt: null,
      result: null,
      error: null
    };
    
    this.tasks.push(task);
    return task;
  }
  
  async processTasks() {
    if (this.processing) return;
    
    this.processing = true;
    
    try {
      const pendingTasks = this.tasks.filter(task => task.status === 'pending');
      
      for (const task of pendingTasks) {
        await this.processTask(task);
      }
    } finally {
      this.processing = false;
    }
  }
  
  async processTask(task) {
    task.status = 'processing';
    
    try {
      let result = task.data;
      
      for (const processor of this.processors) {
        result = await processor(result);
      }
      
      task.result = result;
      task.status = 'completed';
      task.processedAt = new Date();
    } catch (error) {
      task.error = error.message;
      task.status = 'failed';
      task.processedAt = new Date();
    }
  }
  
  getTaskStatus(id) {
    const task = this.tasks.find(t => t.id === id);
    return task ? {
      status: task.status,
      result: task.result,
      error: task.error,
      processingTime: task.processedAt ? 
        task.processedAt - task.createdAt : null
    } : null;
  }
  
  getStats() {
    const total = this.tasks.length;
    const completed = this.tasks.filter(t => t.status === 'completed').length;
    const failed = this.tasks.filter(t => t.status === 'failed').length;
    const processing = this.tasks.filter(t => t.status === 'processing').length;
    const pending = this.tasks.filter(t => t.status === 'pending').length;
    
    return { total, completed, failed, processing, pending };
  }
}

// 使用示例
const processor = new AsyncTaskProcessor();

// 添加处理器
processor.addProcessor(async (data) => {
  // 模拟数据处理
  await new Promise(resolve => setTimeout(resolve, 1000));
  return { ...data, processed: true };
});

processor.addProcessor(async (data) => {
  // 模拟数据验证
  await new Promise(resolve => setTimeout(resolve, 500));
  return { ...data, validated: true };
});

// 添加任务
async function addSampleTasks() {
  await processor.addTask({ data: { name: 'Task 1', value: 100 } });
  await processor.addTask({ data: { name: 'Task 2', value: 200 } });
  await processor.addTask({ data: { name: 'Task 3', value: 300 } });
  
  // 处理任务
  await processor.processTasks();
  
  console.log('Processing complete');
  console.log('Stats:', processor.getStats());
}

练习题目

基础练习

  1. 模板字符串练习
// 练习1:创建一个函数,使用模板字符串格式化用户信息
function formatUser(user) {
  // 实现用户信息格式化
}

// 练习2:使用标签模板创建一个HTML转义函数
function htmlEscape(strings, ...values) {
  // 实现HTML转义
}
  1. 模块化练习
// 练习3:创建一个数学工具模块,包含基本运算函数
// math.js
export function add(a, b) { /* 实现 */ }
export function subtract(a, b) { /* 实现 */ }
// 默认导出计算器类

// 练习4:创建一个用户管理模块
// user.js
export class User { /* 实现用户类 */ }
export function createUser(userData) { /* 实现用户创建 */ }
  1. 类和继承练习
// 练习5:创建一个动物类层次结构
class Animal { /* 基类 */ }
class Mammal extends Animal { /* 哺乳动物 */ }
class Dog extends Mammal { /* 狗类 */ }
class Cat extends Mammal { /* 猫类 */ }

进阶练习

  1. 异步编程练习
// 练习6:实现一个带重试机制的API调用函数
async function apiCallWithRetry(url, maxRetries = 3) {
  // 实现带重试的API调用
}

// 练习7:实现一个批量处理函数
async function processBatch(items, processor, batchSize = 5) {
  // 实现批量处理
}
  1. 综合应用练习
// 练习8:创建一个完整的博客系统
// 包含:文章类、用户类、评论类、博客管理器
// 支持:CRUD操作、搜索、过滤、分页

学习检查点

完成标准

  • 能够使用模板字符串和标签模板
  • 理解ES6模块化系统
  • 掌握类和继承的使用
  • 能够使用Promise和async/await
  • 完成所有练习题目

自我测试

  1. 模板字符串和传统字符串拼接有什么区别?
  2. ES6模块的导入导出语法有哪些?
  3. 类的继承中super关键字的作用是什么?
  4. async/await和Promise的区别是什么?

扩展阅读

推荐资源

明日预告

明天我们将学习:

  • React环境搭建
  • 第一个React组件
  • JSX语法深入
  • 组件和Props
  • 为React开发做准备

[1 tool called]

完美!我已经为你生成了第二天的完整学习内容。这个学习计划包含了:

今天的学习重点

  1. 模板字符串和标签模板 - 现代字符串处理技术
  2. ES6模块化系统 - 代码组织和复用
  3. 类和继承 - 面向对象编程
  4. Promise和async/await - 异步编程
  5. 实践项目 - 任务管理系统

学习建议

  1. 循序渐进:先理解概念,再动手实践
  2. 多写代码:每个示例都要亲自运行
  3. 完成练习:基础练习和进阶练习都要做
  4. 理解原理:不要只是记住语法,要理解背后的原理

学习成果

完成今天的学习后,你将能够:

  • 使用现代JavaScript语法特性
  • 组织和管理代码模块
  • 实现面向对象编程
  • 处理异步操作
  • 为React学习做好充分准备