=====歡迎來到編程星辰海的博客講解======
看完可以給一個免費的三連嗎,謝謝大佬!
目錄
一、知識體系詳解
1. 變量與作用域
2. 箭頭函數特性
3. 數組高階函數
4. DOM操作原理
5. 事件傳播機制
6. 閉包核心原理
7. 原型繼承體系
8. Promise工作流程
二、綜合案例:用戶管理系統
1. HTML結構
2. JavaScript代碼(app.js)
三、實現效果
四、學習要點總結
五、擴展學習推薦
官方文檔
優質文章
一、知識體系詳解
1. 變量與作用域
JAVASCRIPT
// var 存在變量提升和函數作用域 console.log(a); // undefined var a = 10;// let/const 塊級作用域 {let b = 20;const MAX = 100; } console.log(b); // ReferenceError
2. 箭頭函數特性
JAVASCRIPT
const obj = {name: 'obj',regularFunc: function() {console.log(this.name); // obj},arrowFunc: () => {console.log(this.name); // undefined(繼承外層this)} }
3. 數組高階函數
JAVASCRIPT
const numbers = [1,2,3,4];// map轉換 const doubled = numbers.map(n => n * 2); // filter篩選 const evens = numbers.filter(n => n%2 === 0);// reduce聚合 const sum = numbers.reduce((acc, cur) => acc + cur, 0);
4. DOM操作原理
JAVASCRIPT
// 創建元素 const div = document.createElement('div'); div.classList.add('box');// 批量插入 const fragment = document.createDocumentFragment(); items.forEach(item => {const li = document.createElement('li');fragment.appendChild(li); }); ul.appendChild(fragment);
5. 事件傳播機制
6. 閉包核心原理
JAVASCRIPT
function createCounter() {let count = 0; // 閉包保護的變量return {increment: () => ++count,getCount: () => count} }
7. 原型繼承體系
JAVASCRIPT
class Animal {constructor(name) {this.name = name;}speak() {console.log(`${this.name} makes a noise`);} }class Dog extends Animal {constructor(name) {super(name);}speak() {super.speak();console.log(`${this.name} barks`);} }
8. Promise工作流程
二、綜合案例:用戶管理系統(這是完整且可運行代碼,有詳細注釋)
1. HTML結構
HTML
<!DOCTYPE html> <html> <head><title>用戶管理系統</title><style>/* CSS樣式 */.container { max-width: 800px; margin: 20px auto; }.search-box { margin-bottom: 20px; }table { width: 100%; border-collapse: collapse; }th, td { padding: 12px; border: 1px solid #ddd; text-align: left; }th { background-color: #f5f5f5; cursor: pointer; }.pagination { margin-top: 20px; }</style> </head> <body><div class="container"><div class="search-box"><input type="text" id="searchInput" placeholder="輸入姓名或郵箱搜索..."></div><div id="userTable"></div><div class="pagination" id="pagination"></div></div><script src="app.js"></script> </body> </html>
2. JavaScript代碼(app.js)
JAVASCRIPT
class UserManager {constructor() {this.users = []; // 原始數據this.filteredUsers = []; // 過濾后數據this.currentPage = 1; // 當前頁碼this.pageSize = 5; // 每頁條數this.init();}/** 初始化方法(使用異步立即執行函數) */async init() {await this.fetchUsers();this.renderTable();this.setupEventListeners();}/** 使用fetch獲取數據(Promise應用) */async fetchUsers() {try {const response = await fetch('https://dummyjson.com/users?limit=20');const data = await response.json();this.users = data.users.map(user => ({id: user.id,name: `${user.firstName} ${user.lastName}`,age: user.age,email: user.email,department: user.company.department}));this.filteredUsers = [...this.users];} catch (error) {console.error('數據加載失敗:', error);}}/** 渲染表格(DOM操作) */renderTable() {const start = (this.currentPage - 1) * this.pageSize;const end = start + this.pageSize;const currentUsers = this.filteredUsers.slice(start, end);// 創建表格結構const table = document.createElement('table');table.innerHTML = `<thead><tr><th data-field="id">ID ▼</th><th data-field="name">姓名 ▼</th><th data-field="age">年齡 ▼</th><th data-field="email">郵箱 ▼</th><th data-field="department">部門 ▼</th></tr></thead><tbody>${currentUsers.map(user => `<tr><td>${user.id}</td><td>${user.name}</td><td>${user.age}</td><td>${user.email}</td><td>${user.department}</td></tr>`).join('')}</tbody>`;// 清空并更新表格const container = document.getElementById('userTable');container.innerHTML = '';container.appendChild(table);// 渲染分頁this.renderPagination();}/** 分頁組件 */renderPagination() {const totalPages = Math.ceil(this.filteredUsers.length / this.pageSize);const pagination = document.getElementById('pagination');// 生成頁碼按鈕pagination.innerHTML = Array.from({length: totalPages}, (_, i) => `<button class="${i + 1 === this.currentPage ? 'active' : ''}" onclick="userManager.goToPage(${i + 1})">${i + 1}</button>`).join(' ');}/** 事件綁定(使用事件委托) */setupEventListeners() {// 搜索功能document.getElementById('searchInput').addEventListener('input', (e) => {const keyword = e.target.value.toLowerCase();this.filteredUsers = this.users.filter(user =>user.name.toLowerCase().includes(keyword) ||user.email.toLowerCase().includes(keyword));this.currentPage = 1;this.renderTable();});// 表頭排序(閉包保存排序狀態)document.querySelector('#userTable').addEventListener('click', (e) => {if (e.target.tagName === 'TH') {const field = e.target.dataset.field;this.sortUsers(field);}});}/** 排序邏輯 */sortUsers(field) {let isAsc = true; // 閉包保存排序方向return () => {this.filteredUsers.sort((a, b) => {if (typeof a[field] === 'string') {return isAsc ? a[field].localeCompare(b[field]): b[field].localeCompare(a[field]);}return isAsc ? a[field] - b[field] : b[field] - a[field];});isAsc = !isAsc;this.renderTable();}}/** 分頁跳轉 */goToPage(page) {this.currentPage = page;this.renderTable();} }// 初始化系統 const userManager = new UserManager();
三、實現效果
四、學習要點總結
-
變量作用域控制
- 使用const/let進行塊級作用域管理
- 使用IIFE管理私有變量
-
異步流程控制
- async/await處理異步操作
- Promise鏈式調用錯誤處理
-
DOM操作優化
- 使用文檔片段批量插入
- 事件委托減少監聽器數量
-
函數式編程
- map/filter/reduce組合使用
- 純函數避免副作用
-
模塊化設計
- 使用Class組織代碼
- 職責單一原則
五、擴展學習推薦
官方文檔
- MDN JavaScript Guide
- ECMAScript 6 入門
- DOM Living Standard
優質文章
- JavaScript 閉包的終極指南
- Promise 使用模式最佳實踐
- 現代 JavaScript 教程
建議通過Chrome開發者工具的Sources面板調試代碼,觀察閉包變量和事件傳播過程,配合console.log驗證程序執行流程。