📅 学习目标

  • 掌握ES6+核心语法特性
  • 理解变量声明和作用域
  • 学会使用箭头函数和解构赋值
  • 为React学习打下坚实基础

⏰ 学习时间安排

总时长:4-5小时

  • 理论学习:2小时
  • 代码实践:2-3小时

🎯 第一部分:变量声明和作用域 (1小时)

1.1 let vs var 的区别

传统var的问题
// 问题1:变量提升
console.log(name); // undefined (不会报错)
var name = 'React';

// 问题2:函数作用域
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100); // 输出: 3, 3, 3
}

// 问题3:重复声明
var count = 1;
var count = 2; // 不会报错,但容易出错
console.log(count); // 2
let的优势
// 1. 块级作用域
{
  let blockScoped = '只在块内有效';
  console.log(blockScoped); // '只在块内有效'
}
// console.log(blockScoped); // ReferenceError: blockScoped is not defined

// 2. 不存在变量提升
// console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 25;

// 3. 暂时性死区 (Temporal Dead Zone)
let x = 1;
{
  // console.log(x); // ReferenceError: Cannot access 'x' before initialization
  let x = 2;
}

// 4. 不能重复声明
let name = 'React';
// let name = 'Vue'; // SyntaxError: Identifier 'name' has already been declared
const的用法
// const声明常量
const PI = 3.14159;
// PI = 3.14; // TypeError: Assignment to constant variable

// const对象和数组
const person = {
  name: 'John',
  age: 30
};

// 可以修改对象属性
person.age = 31; // 允许
person.city = 'New York'; // 允许

// 不能重新赋值
// person = {}; // TypeError: Assignment to constant variable

const numbers = [1, 2, 3];
numbers.push(4); // 允许
numbers[0] = 10; // 允许

// 不能重新赋值
// numbers = [5, 6, 7]; // TypeError: Assignment to constant variable

1.2 作用域链和闭包

// 作用域链示例
function outerFunction() {
  const outerVariable = 'I am outer';
  
  function innerFunction() {
    const innerVariable = 'I am inner';
    console.log(outerVariable); // 可以访问外部变量
    console.log(innerVariable); // 可以访问内部变量
  }
  
  return innerFunction;
}

const myFunction = outerFunction();
myFunction(); // 输出: 'I am outer', 'I am inner'

// 闭包的实际应用
function createCounter() {
  let count = 0;
  
  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count
  };
}

const counter = createCounter();
console.log(counter.getCount()); // 0
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1

🏹 第二部分:箭头函数 (1小时)

2.1 箭头函数语法

基本语法对比
// 传统函数
function add(a, b) {
  return a + b;
}

// 箭头函数
const add = (a, b) => a + b;

// 单个参数可以省略括号
const square = x => x * x;

// 无参数需要空括号
const greet = () => 'Hello World';

// 多行函数体需要大括号和return
const complexFunction = (a, b) => {
  const sum = a + b;
  const product = a * b;
  return { sum, product };
};
箭头函数的不同写法
// 1. 单行表达式(自动返回)
const double = x => x * 2;

// 2. 多行函数体
const processData = (data) => {
  const filtered = data.filter(item => item.active);
  const sorted = filtered.sort((a, b) => a.priority - b.priority);
  return sorted;
};

// 3. 返回对象(需要括号)
const createUser = (name, age) => ({ name, age, isActive: true });

// 4. 返回函数
const createMultiplier = (factor) => (number) => number * factor;
const double = createMultiplier(2);
console.log(double(5)); // 10

2.2 this绑定差异

// 传统函数的this绑定
const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, I'm ${this.name}`);
  },
  greetDelayed: function() {
    setTimeout(function() {
      console.log(`Hello, I'm ${this.name}`); // this指向全局对象或undefined
    }, 1000);
  }
};

person.greet(); // "Hello, I'm Alice"
person.greetDelayed(); // "Hello, I'm undefined"

// 箭头函数的this绑定
const personArrow = {
  name: 'Bob',
  greet: function() {
    console.log(`Hello, I'm ${this.name}`);
  },
  greetDelayed: function() {
    setTimeout(() => {
      console.log(`Hello, I'm ${this.name}`); // this指向personArrow
    }, 1000);
  }
};

personArrow.greet(); // "Hello, I'm Bob"
personArrow.greetDelayed(); // "Hello, I'm Bob"

2.3 箭头函数的实际应用

// 数组方法中的箭头函数
const numbers = [1, 2, 3, 4, 5];

// map方法
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// filter方法
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

// reduce方法
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

// 链式调用
const result = numbers
  .filter(n => n > 2)
  .map(n => n * n)
  .reduce((acc, curr) => acc + curr, 0);
console.log(result); // 50 (3² + 4² + 5²)

第三部分:解构赋值 (1小时)

3.1 数组解构

// 基本数组解构
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
console.log(first, second, third); // red green blue

// 跳过元素
const [first, , third] = colors;
console.log(first, third); // red blue

// 默认值
const [a, b, c, d = 'yellow'] = colors;
console.log(d); // yellow

// 剩余元素
const [primary, ...others] = colors;
console.log(primary); // red
console.log(others); // ['green', 'blue']

// 交换变量
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1

// 函数返回多个值
function getCoordinates() {
  return [10, 20];
}
const [x, y] = getCoordinates();
console.log(x, y); // 10 20

3.2 对象解构

// 基本对象解构
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const { name, age, city } = person;
console.log(name, age, city); // John 30 New York

// 重命名变量
const { name: fullName, age: years } = person;
console.log(fullName, years); // John 30

// 默认值
const { name, age, country = 'USA' } = person;
console.log(country); // USA

// 嵌套解构
const user = {
  id: 1,
  profile: {
    name: 'Alice',
    address: {
      street: '123 Main St',
      city: 'Boston'
    }
  }
};

const { profile: { name, address: { city } } } = user;
console.log(name, city); // Alice Boston

// 函数参数解构
function greetUser({ name, age = 0 }) {
  return `Hello ${name}, you are ${age} years old`;
}

console.log(greetUser({ name: 'Bob' })); // Hello Bob, you are 0 years old
console.log(greetUser({ name: 'Alice', age: 25 })); // Hello Alice, you are 25 years old

3.3 解构的实际应用

// API响应处理
const apiResponse = {
  status: 'success',
  data: {
    users: [
      { id: 1, name: 'John', email: 'john@example.com' },
      { id: 2, name: 'Jane', email: 'jane@example.com' }
    ],
    total: 2
  }
};

const { data: { users, total } } = apiResponse;
console.log(users, total); // 用户数组和总数

// 配置对象解构
const config = {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  retries: 3
};

function makeRequest({ apiUrl, timeout = 3000, retries = 1 }) {
  console.log(`Making request to ${apiUrl} with timeout ${timeout} and ${retries} retries`);
}

makeRequest(config);

// 事件处理
function handleClick({ target, clientX, clientY }) {
  console.log(`Clicked on ${target.tagName} at (${clientX}, ${clientY})`);
}

// 模拟事件对象
const mockEvent = {
  target: { tagName: 'BUTTON' },
  clientX: 100,
  clientY: 200
};
handleClick(mockEvent);

第四部分:实践项目 (1-2小时)

项目:用户管理系统

创建一个完整的用户管理系统,练习所有今天学到的ES6语法。

// userManager.js
class UserManager {
  constructor() {
    this.users = [];
    this.currentId = 1;
  }

  // 添加用户
  addUser({ name, email, age = 0, isActive = true }) {
    const user = {
      id: this.currentId++,
      name,
      email,
      age,
      isActive,
      createdAt: new Date()
    };
    this.users.push(user);
    return user;
  }

  // 获取所有用户
  getAllUsers() {
    return [...this.users]; // 返回副本,避免直接修改
  }

  // 根据ID获取用户
  getUserById(id) {
    return this.users.find(user => user.id === id);
  }

  // 更新用户
  updateUser(id, updates) {
    const userIndex = this.users.findIndex(user => user.id === id);
    if (userIndex !== -1) {
      this.users[userIndex] = { ...this.users[userIndex], ...updates };
      return this.users[userIndex];
    }
    return null;
  }

  // 删除用户
  deleteUser(id) {
    const userIndex = this.users.findIndex(user => user.id === id);
    if (userIndex !== -1) {
      const [deletedUser] = this.users.splice(userIndex, 1);
      return deletedUser;
    }
    return null;
  }

  // 搜索用户
  searchUsers({ name, email, isActive }) {
    return this.users.filter(user => {
      const nameMatch = !name || user.name.toLowerCase().includes(name.toLowerCase());
      const emailMatch = !email || user.email.toLowerCase().includes(email.toLowerCase());
      const activeMatch = isActive === undefined || user.isActive === isActive;
      
      return nameMatch && emailMatch && activeMatch;
    });
  }

  // 获取用户统计
  getStats() {
    const total = this.users.length;
    const active = this.users.filter(user => user.isActive).length;
    const inactive = total - active;
    const averageAge = total > 0 ? this.users.reduce((sum, user) => sum + user.age, 0) / total : 0;

    return { total, active, inactive, averageAge: Math.round(averageAge) };
  }

  // 批量操作
  batchUpdate(ids, updates) {
    const results = [];
    ids.forEach(id => {
      const result = this.updateUser(id, updates);
      results.push({ id, success: !!result, user: result });
    });
    return results;
  }

  // 导出用户数据
  exportUsers() {
    return this.users.map(({ id, name, email, age, isActive, createdAt }) => ({
      id,
      name,
      email,
      age,
      isActive,
      createdAt: createdAt.toISOString()
    }));
  }
}

// 使用示例
const userManager = new UserManager();

// 添加用户
const user1 = userManager.addUser({
  name: 'John Doe',
  email: 'john@example.com',
  age: 30
});

const user2 = userManager.addUser({
  name: 'Jane Smith',
  email: 'jane@example.com',
  age: 25
});

const user3 = userManager.addUser({
  name: 'Bob Johnson',
  email: 'bob@example.com',
  age: 35,
  isActive: false
});

console.log('所有用户:', userManager.getAllUsers());

// 搜索用户
const activeUsers = userManager.searchUsers({ isActive: true });
console.log('活跃用户:', activeUsers);

// 更新用户
const updatedUser = userManager.updateUser(1, { age: 31, city: 'New York' });
console.log('更新的用户:', updatedUser);

// 获取统计信息
const stats = userManager.getStats();
console.log('用户统计:', stats);

// 批量更新
const batchResults = userManager.batchUpdate([1, 2], { city: 'San Francisco' });
console.log('批量更新结果:', batchResults);

// 导出数据
const exportedData = userManager.exportUsers();
console.log('导出的数据:', exportedData);

高级练习:数据处理器

// dataProcessor.js
class DataProcessor {
  constructor() {
    this.data = [];
    this.filters = [];
    this.sorters = [];
  }

  // 添加数据
  addData(newData) {
    this.data = [...this.data, ...newData];
    return this;
  }

  // 添加过滤器
  addFilter(filterFn) {
    this.filters.push(filterFn);
    return this;
  }

  // 添加排序器
  addSorter(sortFn) {
    this.sorters.push(sortFn);
    return this;
  }

  // 处理数据
  process() {
    let result = [...this.data];
    
    // 应用过滤器
    this.filters.forEach(filter => {
      result = result.filter(filter);
    });
    
    // 应用排序器
    this.sorters.forEach(sorter => {
      result.sort(sorter);
    });
    
    return result;
  }

  // 重置
  reset() {
    this.filters = [];
    this.sorters = [];
    return this;
  }
}

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

// 添加数据
const products = [
  { id: 1, name: 'Laptop', price: 999, category: 'Electronics', inStock: true },
  { id: 2, name: 'Book', price: 19, category: 'Education', inStock: true },
  { id: 3, name: 'Phone', price: 699, category: 'Electronics', inStock: false },
  { id: 4, name: 'Pen', price: 2, category: 'Office', inStock: true },
  { id: 5, name: 'Tablet', price: 499, category: 'Electronics', inStock: true }
];

processor.addData(products);

// 添加过滤器和排序器
processor
  .addFilter(product => product.inStock) // 只显示有库存的
  .addFilter(product => product.price > 10) // 价格大于10
  .addSorter((a, b) => a.price - b.price) // 按价格升序
  .addSorter((a, b) => a.name.localeCompare(b.name)); // 按名称字母顺序

// 处理数据
const processedData = processor.process();
console.log('处理后的数据:', processedData);

// 重置并重新处理
processor.reset();
const allData = processor.process();
console.log('所有数据:', allData);

练习题目

基础练习

  1. 变量声明练习
// 练习1:修复以下代码中的问题
var name = 'React';
var name = 'Vue'; // 这里应该报错
console.log(name);

// 练习2:使用let和const重写以下代码
var count = 0;
var increment = function() {
  count++;
  return count;
};
  1. 箭头函数练习
// 练习3:将以下函数转换为箭头函数
function multiply(a, b) {
  return a * b;
}

function greet(name) {
  return 'Hello, ' + name + '!';
}

function getFullName(firstName, lastName) {
  return firstName + ' ' + lastName;
}
  1. 解构赋值练习
// 练习4:从以下对象中解构出name和age
const person = {
  name: 'Alice',
  age: 30,
  city: 'New York',
  country: 'USA'
};

// 练习5:从以下数组中解构出前三个元素
const colors = ['red', 'green', 'blue', 'yellow', 'purple'];

进阶练习

  1. 综合应用
// 练习6:创建一个函数,接收用户数组,返回活跃用户的姓名列表
const users = [
  { id: 1, name: 'John', isActive: true },
  { id: 2, name: 'Jane', isActive: false },
  { id: 3, name: 'Bob', isActive: true }
];

// 使用箭头函数和解构赋值实现
  1. 数据处理
// 练习7:处理以下数据,返回价格大于100且库存大于0的商品
const products = [
  { name: 'Laptop', price: 999, stock: 5 },
  { name: 'Mouse', price: 25, stock: 0 },
  { name: 'Keyboard', price: 75, stock: 10 },
  { name: 'Monitor', price: 299, stock: 3 }
];

🎯 学习检查点

完成标准

  • 能够正确使用let、const声明变量
  • 理解箭头函数的语法和this绑定
  • 掌握数组和对象的解构赋值
  • 能够编写简单的数据处理函数
  • 完成所有练习题目

自我测试

  1. 解释let和var的主要区别
  2. 箭头函数在什么情况下不能使用?
  3. 解构赋值时如何设置默认值?
  4. 如何从嵌套对象中解构数据?

扩展阅读

推荐资源

明日预告

明天我们将学习:

  • 模板字符串和标签模板
  • 模块化开发(import/export)
  • 类和继承
  • 为React学习做更深入的准备

记住,学习编程最重要的是多动手实践!每个代码示例都要亲自运行一遍,理解每一行代码的作用。

[1 tool called]

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

今天的学习重点

  1. 变量声明和作用域 - let/const vs var的深入理解
  2. 箭头函数 - 语法、this绑定、实际应用
  3. 解构赋值 - 数组和对象的解构技巧
  4. 实践项目 - 用户管理系统和数据处理器

学习建议

  1. 按顺序学习:先理解概念,再动手实践
  2. 多写代码:每个示例都要亲自运行
  3. 完成练习:基础练习和进阶练习都要做
  4. 自我测试:确保理解每个概念

学习成果

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

  • 正确使用ES6+语法特性
  • 理解JavaScript的作用域和闭包
  • 掌握函数式编程的基础
  • 为React学习打下坚实基础
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐