JavaScript编程语言如何驱动前端开发从基础语法到框架应用的全面解析与实战技巧分享

引言:JavaScript在前端开发中的核心地位
JavaScript作为现代Web开发的基石,已经从一个简单的脚本语言演变为功能强大的全栈开发工具。在前端领域,JavaScript扮演着无可替代的角色,它负责处理用户交互、操作DOM、管理数据状态、构建复杂的单页应用等重要任务。
随着Web技术的飞速发展,JavaScript生态系统变得异常庞大,从基础的语法特性到复杂的框架架构,从传统的DOM操作到现代的组件化开发,掌握JavaScript及其相关技术栈已成为前端开发者的必备技能。本文将全面解析JavaScript如何驱动前端开发,从基础语法到框架应用,并分享实战中的技巧和最佳实践。
JavaScript基础语法详解
变量声明与作用域
JavaScript提供了三种变量声明方式:
var
、
let
和
const
。理解它们的区别对于编写健壮的代码至关重要。
// var声明的变量存在变量提升和函数作用域
function varExample() {
console.log(x); // 输出undefined,变量提升
var x = 10;
if (true) {
var x = 20; // 同一个函数作用域内
console.log(x); // 输出20
}
console.log(x); // 输出20
}

// let和const具有块级作用域
function letConstExample() {
let y = 10;
const z = 5;

if (true) {
let y = 20; // 块级作用域,不影响外层
// const z = 15; // 错误,不能重复声明常量
console.log(y); // 输出20
}
console.log(y); // 输出10

// const声明的变量不能重新赋值
// z = 10; // 错误
}

// 实际应用:循环中的变量声明
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); // 输出3,3,3
}

for (let j = 0; j < 3; j++) { setTimeout(() => console.log(j), 100); // 输出0,1,2
}
实战技巧
:始终使用
const
声明变量,仅在需要重新赋值时使用
let
,避免使用
var
。这可以减少许多潜在的错误。
数据类型与类型转换
JavaScript有8种数据类型:7种原始类型(Undefined、Null、Boolean、String、Number、BigInt、Symbol)和1种对象类型。
// 原始类型与引用类型的区别
let a = 10;
let b = a; // 值复制
b = 20;
console.log(a); // 10

let obj1 = { name: ‘Alice’ };
let obj2 = obj1; // 引用复制
obj2.name = ‘Bob’;
console.log(obj1.name); // ‘Bob’

// 类型检测
console.log(typeof 42); // “number”
console.log(typeof “hello”); // “string”
console.log(typeof true); // “boolean”
console.log(typeof undefined); // “undefined”
console.log(typeof null); // “object”(历史遗留问题)
console.log(typeof []); // “object”
console.log(typeof {}); // “object”

// 类型转换
console.log(Number(“123”)); // 123
console.log(Number(“abc”)); // NaN
console.log(String(123)); // “123”
console.log(Boolean(0)); // false
console.log(Boolean(“”)); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(“0”)); // true

// 实战:表单输入验证
function validateInput(input) {
const value = Number(input);
if (isNaN(value)) {
return “请输入有效的数字”;
}
if (value < 0) { return "数字不能为负数"; } return "验证通过"; } 实战技巧 :使用严格相等 === 避免隐式类型转换带来的问题,使用 Number.isNaN() 或 Object.is() 进行更精确的比较。 函数与箭头函数 JavaScript的函数是一等公民,可以作为参数传递、作为返回值、赋值给变量。 // 函数声明与函数表达式 function sayHello(name) { return `Hello, ${name}`; } const greet = function(name) { return `Hi, ${name}`; }; // 箭头函数 const arrowGreet = (name) => {
return `Hey, ${name}`;
};

// 箭头函数的简写形式
const add = (a, b) => a + b;
const square = x => x * x;

// 箭头函数与普通函数的区别
const obj = {
value: 42,
regularFunc: function() {
console.log(this.value); // 42
},
arrowFunc: () => {
console.log(this.value); // undefined(箭头函数没有自己的this)
}
};

// 实战:数组方法中的回调函数
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15

// 实战:防抖函数(Debounce)
function debounce(func, wait) {
let timeout;
return function executedFunction(…args) {
const later = () => {
clearTimeout(timeout);
func(…args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

// 使用示例
const handleSearch = debounce((query) => {
console.log(‘Searching for:’, query);
}, 300);
实战技巧
:箭头函数适合用于回调函数和需要继承外层
this
的场景,但不适合定义对象方法或需要动态
this
的场景。
面向对象编程
JavaScript通过原型链实现面向对象编程,ES6引入了
class
语法糖。
// 传统原型链方式
function Person(name, age) {
this.name = name;
this.age = age;
}

Person.prototype.sayHello = function() {
return `Hello, I’m ${this.name}, ${this.age} years old`;
};

const person1 = new Person(‘Alice’, 30);
console.log(person1.sayHello());

// ES6 class语法
class Animal {
constructor(name) {
this.name = name;
}

speak() {
return `${this.name} makes a sound.`;
}
}

class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}

speak() {
return `${this.name} barks!`;
}

fetch() {
return `${this.name} fetches the ball.`;
}
}

const dog = new Dog(‘Buddy’, ‘Golden Retriever’);
console.log(dog.speak()); // “Buddy barks!”
console.log(dog.fetch()); // “Buddy fetches the ball.”

// 实战:创建可复用的表单验证类
class FormValidator {
constructor(rules) {
this.rules = rules;
this.errors = {};
}

validate(formData) {
this.errors = {};

for (const [field, value] of Object.entries(formData)) {
if (this.rules[field]) {
const result = this.rules[field](value);
if (result !== true) {
this.errors[field] = result;
}
}
}

return Object.keys(this.errors).length === 0;
}

getErrors() {
return this.errors;
}
}

// 使用示例
const validator = new FormValidator({
email: (value) => /\S+@\S+\.\S+/.test(value) || “Invalid email format”,
password: (value) => value.length >= 8 || “Password must be at least 8 characters”,
age: (value) => Number(value) >= 18 || “Must be 18 or older”
});

const formData = {
email: “user@example.com”,
password: “short”,
age: “17”
};

if (!validator.validate(formData)) {
console.log(validator.getErrors());
// { password: ‘Password must be at least 8 characters’, age: ‘Must be 18 or older’ }
}
实战技巧
:优先使用
class
语法,但要理解其背后的原型机制。使用
extends
实现继承时,务必调用
super()
。
DOM操作与事件处理
DOM查询与修改
DOM(文档对象模型)是JavaScript与HTML交互的桥梁。
// 查询元素
const elementById = document.getElementById(‘myId’);
const elementsByClass = document.getElementsByClassName(‘myClass’);
const elementsByTag = document.getElementsByTagName(‘div’);
const elementByQuery = document.querySelector(‘.myClass’);
const elementsByQueryAll = document.querySelectorAll(‘div.myClass’);

// 实战:动态创建和插入元素
function createTodoItem(text) {
const li = document.createElement(‘li’);
li.className = ‘todo-item’;
li.textContent = text;

const deleteBtn = document.createElement(‘button’);
deleteBtn.textContent = ‘Delete’;
deleteBtn.onclick = () => li.remove();

li.appendChild(deleteBtn);
return li;
}

function addTodo(text) {
const todoList = document.getElementById(‘todoList’);
const todoItem = createTodoItem(text);
todoList.appendChild(todoItem);
}

// 实战:批量操作优化
function updateMultipleElements() {
// 避免在循环中反复查询DOM
const container = document.getElementById(‘container’);
const items = container.querySelectorAll(‘.item’);

// 使用DocumentFragment进行批量插入
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) { const div = document.createElement('div'); div.textContent = `Item ${i}`; fragment.appendChild(div); } container.appendChild(fragment); } 事件处理 // 事件监听 const button = document.getElementById('myButton'); button.addEventListener('click', function(event) { console.log('Button clicked!', event.target); }); // 事件委托(推荐) document.getElementById('todoList').addEventListener('click', function(event) { if (event.target.tagName === 'BUTTON') { // 删除操作 event.target.parentElement.remove(); } }); // 自定义事件 const customEvent = new CustomEvent('custom', { detail: { message: 'Hello' } }); document.addEventListener('custom', (e) => {
console.log(e.detail.message); // “Hello”
});

document.dispatchEvent(customEvent);

// 实战:拖拽功能实现
function makeDraggable(element) {
let isDragging = false;
let startX, startY, initialX, initialY;

element.addEventListener(‘mousedown’, (e) => {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
initialX = element.offsetLeft;
initialY = element.offsetTop;
element.style.cursor = ‘grabbing’;
});

document.addEventListener(‘mousemove’, (e) => {
if (!isDragging) return;

const dx = e.clientX – startX;
const dy = e.clientY – startY;

element.style.left = `${initialX + dx}px`;
element.style.top = `${initialY + dy}px`;
});

document.addEventListener(‘mouseup’, () => {
isDragging = false;
element.style.cursor = ‘grab’;
});
}

// 使用示例
const draggableElement = document.getElementById(‘dragMe’);
if (draggableElement) {
makeDraggable(draggableElement);
}
实战技巧
:始终使用事件委托来处理动态元素的事件,避免内存泄漏(及时移除不再需要的事件监听器)。
异步编程与AJAX
Promise与async/await
// Promise基础
function fetchData(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(‘GET’, url);
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(`HTTP ${xhr.status}`));
}
};
xhr.onerror = () => reject(new Error(‘Network error’));
xhr.send();
});
}

// 使用Promise链
fetchData(‘https://api.example.com/data’)
.then(data => {
console.log(‘Data received:’, data);
return JSON.parse(data);
})
.then(parsed => processData(parsed))
.catch(error => console.error(‘Error:’, error))
.finally(() => console.log(‘Request completed’));

// async/await语法
async function getUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(‘Failed to fetch user:’, error);
throw error;
}
}

// 并行执行
async function fetchMultipleUsers(userIds) {
const promises = userIds.map(id =>
fetch(`https://api.example.com/users/${id}`).then(r => r.json())
);

try {
const users = await Promise.all(promises);
return users;
} catch (error) {
console.error(‘One or more requests failed:’, error);
return [];
}
}

// 实战:带重试机制的请求
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(url, options); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
AJAX与Fetch API
// 使用Fetch API
async function sendFormData(formData) {
try {
const response = await fetch(‘/api/submit’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify(formData),
});

if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

const result = await response.json();
return result;
} {
console.error(‘Submission failed:’, error);
throw error;
}
}

// 实战:文件上传与进度监控
function uploadFile(file, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();

xhr.upload.addEventListener(‘progress’, (e) => {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
onProgress(percentComplete);
}
});

xhr.addEventListener(‘load’, () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(`Upload failed: ${xhr.status}`));
}
});

xhr.addEventListener(‘error’, () => reject(new Error(‘Network error’)));

const formData = new FormData();
formData.append(‘file’, file);

xhr.open(‘POST’, ‘/api/upload’);
xhr.send(formData);
});
}

// 使用示例
const fileInput = document.getElementById(‘fileInput’);
fileInput.addEventListener(‘change’, async (e) => {
const file = e.target.files[0];
if (!file) return;

try {
const result = await uploadFile(file, (progress) => {
console.log(`Upload progress: ${progress.toFixed(2)}%`);
document.getElementById(‘progressBar’).style.width = `${progress}%`;
});
console.log(‘Upload successful:’, result);
} catch (error) {
console.error(‘Upload failed:’, error);
}
});
实战技巧
:使用
async/await
处理异步代码,使用
Promise.all
并行处理多个请求,使用
try/catch
进行错误处理。
ES6+高级特性
解构赋值与展开运算符
// 对象解构
const user = { name: ‘Alice’, age: 30, city: ‘NYC’ };
const { name, age } = user;
console.log(name, age); // “Alice” 30

// 数组解构
const [first, second, …rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3,4,5]

// 函数参数解构
function createUser({ name, age = 18, city = ‘Unknown’ }) {
return { name, age, city };
}

// 展开运算符
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = […arr1, …arr2]; // [1,2,3,4,5,6]

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, …obj1, d: 4 }; // { c: 3, a: 1, b: 2, d: 4 }

// 实战:不可变数据操作
function updateUser(user, updates) {
return { …user, …updates };
}

const originalUser = { name: ‘Alice’, age: 30 };
const updatedUser = updateUser(originalUser, { age: 31 });
console.log(originalUser); // { name: ‘Alice’, age: 30 }(未改变)
console.log(updatedUser); // { name: ‘Alice’, age: 31 }

// 实战:函数参数默认值
function createProduct(name, price = 0, { category = ‘General’, inStock = true } = {}) {
return { name, price, category, inStock };
}

const product = createProduct(‘Laptop’, 999, { category: ‘Electronics’ });
模块化编程
// ES6模块导出
// utils.js
export const PI = 3.14159;

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

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

// main.js
import multiply, { PI, sum } from ‘./utils.js’;
import * as utils from ‘./utils.js’;

console.log(PI); // 3.14159
console.log(sum(1, 2)); // 3
console.log(multiply(2, 3)); // 6
console.log(utils.PI); // 3.14159

// 实战:模块化组织代码
// api/client.js
export class ApiClient {
constructor(baseURL) {
this.baseURL = baseURL;
}

async get(endpoint) {
const response = await fetch(`${this.baseURL}${endpoint}`);
return response.json();
}
}

// api/userService.js
import { ApiClient } from ‘./client.js’;

export class UserService {
constructor() {
this.client = new ApiClient(‘https://api.example.com’);
}

async getUser(id) {
return this.client.get(`/users/${id}`);
}
}

// app.js
import { UserService } from ‘./api/userService.js’;

const userService = new UserService();
userService.getUser(1).then(user => console.log(user));
其他重要特性
// 模板字符串
const name = ‘Alice’;
const greeting = `Hello, ${name}! Today is ${new Date().toLocaleDateString()}.`;

// 可选链操作符
const user = { profile: { name: ‘Alice’ } };
console.log(user?.profile?.name); // “Alice”
console.log(user?.settings?.theme); // undefined(不会报错)

// 空值合并操作符
const config = { timeout: null };
const timeout = config.timeout ?? 3000; // 3000

// BigInt
const bigNumber = 9007199254740991n;
const result = bigNumber + 1n; // 9007199254740992n

// Symbol
const uniqueKey = Symbol(‘description’);
const obj = { [uniqueKey]: ‘value’ };
console.log(obj[uniqueKey]); // “value”

// 实战:使用Symbol实现私有属性
const _privateData = Symbol(‘privateData’);

class MyClass {
constructor() {
this[_privateData] = { secret: ‘hidden’ };
}

getPrivate() {
return this[_privateData];
}
}

const instance = new MyClass();
console.log(instance.getPrivate()); // { secret: ‘hidden’ }
console.log(Object.keys(instance)); // [](Symbol属性不会被枚举)
实战技巧
:使用可选链
?.
和空值合并
??
简化代码,使用模板字符串提高可读性,使用Symbol创建唯一标识符。
现代前端框架应用
React框架深度解析
React是目前最流行的前端框架之一,基于组件化思想和虚拟DOM。
// React组件定义(函数组件)
import React, { useState, useEffect, useCallback } from ‘react’;

// 计数器组件
function Counter() {
const [count, setCount] = useState(0);

const increment = useCallback(() => {
setCount(prev => prev + 1);
}, []);

const decrement = useCallback(() => {
setCount(prev => prev – 1);
}, []);

return (


{count}

);
}

// 带副作用的组件
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
let isMounted = true;

async function fetchUser() {
try {
setLoading(true);
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) throw new Error(‘Failed to fetch’);
const data = await response.json();
if (isMounted) setUser(data);
} catch (err) {
if (isMounted) setError(err.message);
} finally {
if (isMounted) setLoading(false);
}
}

fetchUser();

return () => {
isMounted = false; // 清理函数,防止内存泄漏
};
}, [userId]); // 依赖数组

if (loading) return

Loading…

;
if (error) return

Error: {error}

;
if (!user) return

No user found

;

return (

{user.name}

{user.email}

);
}

// 自定义Hook
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});

useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error);
}
}, [key, value]);

return [value, setValue];
}

// 使用自定义Hook
function TodoApp() {
const [todos, setTodos] = useLocalStorage(‘todos’, []);
const [input, setInput] = useState(”);

const addTodo = useCallback(() => {
if (input.trim()) {
setTodos([…todos, { id: Date.now(), text: input, done: false }]);
setInput(”);
}
}, [input, todos, setTodos]);

const toggleTodo = useCallback((id) => {
setTodos(todos.map(todo =>
todo.id === id ? { …todo, done: !todo.done } : todo
));
}, [todos, setTodos]);

return (

setInput(e.target.value)}
onKeyPress={e => e.key === ‘Enter’ && addTodo()}
/>

    {todos.map(todo => (

  • toggleTodo(todo.id)}>

    {todo.text}
  • ))}

);
}
React实战技巧
:
使用自定义Hook
:将可复用的逻辑提取到自定义Hook中
依赖数组优化
:正确使用
useEffect
和
useCallback
的依赖数组
避免不必要的渲染
:使用
React.memo
、
useMemo
和
useCallback
状态提升
:将共享状态提升到最近的共同祖先组件
使用Context API
:避免深层props传递
Vue.js框架深度解析
Vue.js以其简洁的API和渐进式框架设计著称。
// Vue 3组合式API
import { ref, reactive, computed, watch, onMounted } from ‘vue’;

// 基础组件
export default {
name: ‘Counter’,
setup() {
const count = ref(0);

const increment = () => {
count.value++;
};

const doubleCount = computed(() => count.value * 2);

watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});

onMounted(() => {
console.log(‘Component mounted’);
});

return {
count,
increment,
doubleCount
};
}
};

// 使用Composition API和

// Vue自定义指令
const vFocus = {
mounted(el) {
el.focus();
}
};

// 全局注册
app.directive('focus', vFocus);

// 使用
//
Vue实战技巧
:
组合式API
:使用
setup
和Composition API组织复杂逻辑
响应式数据
:正确使用
ref
和
reactive
计算属性
:使用
computed
缓存计算结果
侦听器
:使用
watch
和
watchEffect
响应数据变化
组件通信
:使用props/emits、provide/inject、状态管理(Pinia)
Angular框架深度解析
Angular是一个全功能的框架,提供完整的解决方案。
// Angular组件
import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import { UserService } from './user.service';
import { Subscription } from 'rxjs';

@Component({
selector: 'app-user-profile',
template: `

Loading...
{{ error }}

{{ user.name | uppercase }}

{{ user.email }}

Age: {{ user.age | age }}

`,
styles: [`
:host {
display: block;
padding: 1rem;
border: 1px solid #ccc;
}
`]
})
export class UserProfileComponent implements OnInit, OnDestroy {
@Input() userId!: number;
@Output() delete = new EventEmitter();

user: any = null;
loading = false;
error: string | null = null;

private subscription: Subscription | null = null;

constructor(private userService: UserService) {}

ngOnInit() {
this.fetchUser();
}

ngOnDestroy() {
this.subscription?.unsubscribe();
}

fetchUser() {
this.loading = true;
this.error = null;

this.subscription = this.userService.getUser(this.userId).subscribe({
next: (data) => {
this.user = data;
this.loading = false;
},
error: (err) => {
this.error = err.message;
this.loading = false;
}
});
}

onDelete() {
this.delete.emit(this.userId);
}
}

// Angular服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class UserService {
private baseUrl = 'https://api.example.com';

constructor(private http: HttpClient) {}

getUser(id: number): Observable {
return this.http.get(`${this.baseUrl}/users/${id}`).pipe(
retry(3), // 重试3次
catchError(this.handleError)
);
}

private handleError(error: any) {
let errorMessage = 'Unknown error!';
if (error.error instanceof ErrorEvent) {
errorMessage = `Error: ${error.error.message}`;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(() => new Error(errorMessage));
}
}

// Angular管道
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'age' })
export class AgePipe implements PipeTransform {
transform(birthDate: string): string {
const age = new Date().getFullYear() - new Date(birthDate).getFullYear();
return `${age} years old`;
}
}
Angular实战技巧
:
依赖注入
:使用构造函数注入服务
RxJS操作符
:使用
catchError
、
retry
、
map
等处理异步流
变更检测
:使用
ChangeDetectorRef
手动控制变更检测
模块化
:合理组织模块结构
路由
:使用路由守卫保护页面
实战项目:构建完整的Todo应用
项目结构
todo-app/
├── index.html
├── css/
│ └── style.css
├── js/
│ ├── app.js
│ ├── storage.js
│ └── ui.js
└── README.md
核心代码实现
// js/storage.js - 本地存储管理
export class TodoStorage {
static KEY = 'todo-app-data';

static getTodos() {
try {
const data = localStorage.getItem(this.KEY);
return data ? JSON.parse(data) : [];
} catch {
return [];
}
}

static saveTodos(todos) {
localStorage.setItem(this.KEY, JSON.stringify(todos));
}

static addTodo(text) {
const todos = this.getTodos();
const newTodo = {
id: Date.now(),
text,
done: false,
createdAt: new Date().toISOString()
};
todos.push(newTodo);
this.saveTodos(todos);
return newTodo;
}

static toggleTodo(id) {
const todos = this.getTodos();
const todo = todos.find(t => t.id === id);
if (todo) {
todo.done = !todo.done;
this.saveTodos(todos);
}
return todo;
}

static deleteTodo(id) {
const todos = this.getTodos();
const filtered = todos.filter(t => t.id !== id);
this.saveTodos(filtered);
return id;
}

static clearCompleted() {
const todos = this.getTodos();
const active = todos.filter(t => !t.done);
this.saveTodos(active);
return active;
}
}

// js/ui.js - UI管理
export class TodoUI {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.input = this.container.querySelector('.todo-input');
this.addButton = this.container.querySelector('.add-button');
this.list = this.container.querySelector('.todo-list');
this.stats = this.container.querySelector('.stats');
this.clearButton = this.container.querySelector('.clear-completed');

this.bindEvents();
}

bindEvents() {
// 添加事项
this.addButton.addEventListener('click', () => this.handleAdd());
this.input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.handleAdd();
});

// 事件委托处理列表点击
this.list.addEventListener('click', (e) => {
if (e.target.classList.contains('toggle')) {
const id = parseInt(e.target.closest('li').dataset.id);
this.onToggle(id);
} else if (e.target.classList.contains('delete')) {
const id = parseInt(e.target.closest('li').dataset.id);
this.onDelete(id);
}
});

// 清空已完成
this.clearButton.addEventListener('click', () => this.onClearCompleted());
}

handleAdd() {
const text = this.input.value.trim();
if (!text) return;

this.onAdd(text);
this.input.value = '';
}

render(todos) {
this.list.innerHTML = todos.map(todo => `


  • ${this.escapeHtml(todo.text)}
  • `).join('');

    this.renderStats(todos);
    }

    renderStats(todos) {
    const total = todos.length;
    const completed = todos.filter(t => t.done).length;
    const active = total - completed;

    this.stats.textContent = `Total: ${total} | Active: ${active} | Completed: ${completed}`;
    this.clearButton.style.display = completed > 0 ? 'block' : 'none';
    }

    escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
    }

    // 事件回调(由外部设置)
    onAdd = null;
    onToggle = null;
    onDelete = null;
    onClearCompleted = null;
    }

    // js/app.js - 应用主逻辑
    import { TodoStorage } from './storage.js';
    import { TodoUI } from './ui.js';

    class TodoApp {
    constructor() {
    this.ui = new TodoUI('todo-app');
    this.todos = TodoStorage.getTodos();

    // 绑定UI事件处理
    this.ui.onAdd = this.addTodo.bind(this);
    this.ui.onToggle = this.toggleTodo.bind(this);
    this.ui.onDelete = this.deleteTodo.bind(this);
    this.ui.onClearCompleted = this.clearCompleted.bind(this);

    this.render();
    }

    addTodo(text) {
    const todo = TodoStorage.addTodo(text);
    this.todos.push(todo);
    this.render();
    }

    toggleTodo(id) {
    const todo = TodoStorage.toggleTodo(id);
    if (todo) {
    const index = this.todos.findIndex(t => t.id === id);
    if (index !== -1) {
    this.todos[index] = todo;
    }
    this.render();
    }
    }

    deleteTodo(id) {
    TodoStorage.deleteTodo(id);
    this.todos = this.todos.filter(t => t.id !== id);
    this.render();
    }

    clearCompleted() {
    this.todos = TodoStorage.clearCompleted();
    this.render();
    }

    render() {
    this.ui.render(this.todos);
    }
    }

    // 应用启动
    document.addEventListener('DOMContentLoaded', () => {
    new TodoApp();
    });
    HTML结构





    Todo App

    Todo App





      CSS样式
      /* css/style.css */
      .todo-container {
      max-width: 500px;
      margin: 2rem auto;
      padding: 2rem;
      background: #f9f9f9;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      }

      .input-group {
      display: flex;
      gap: 0.5rem;
      margin-bottom: 1rem;
      }

      .todo-input {
      flex: 1;
      padding: 0.75rem;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 1rem;
      }

      .add-button {
      padding: 0.75rem 1.5rem;
      background: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      }

      .add-button:hover {
      background: #0056b3;
      }

      .todo-list {
      list-style: none;
      padding: 0;
      margin: 0;
      }

      .todo-list li {
      display: flex;
      align-items: center;
      padding: 0.75rem;
      background: white;
      margin-bottom: 0.5rem;
      border-radius: 4px;
      border: 1px solid #eee;
      }

      .todo-list li.completed {
      opacity: 0.6;
      text-decoration: line-through;
      }

      .todo-list li span {
      flex: 1;
      margin: 0 0.5rem;
      }

      .toggle {
      cursor: pointer;
      }

      .delete {
      background: #dc3545;
      color: white;
      border: none;
      border-radius: 50%;
      width: 24px;
      height: 24px;
      cursor: pointer;
      font-weight: bold;
      }

      .delete:hover {
      background: #c82333;
      }

      .stats {
      margin: 1rem 0;
      padding: 0.75rem;
      background: #e9ecef;
      border-radius: 4px;
      text-align: center;
      font-size: 0.9rem;
      }

      .clear-completed {
      width: 100%;
      padding: 0.75rem;
      background: #28a745;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      display: none;
      }

      .clear-completed:hover {
      background: #218838;
      }
      性能优化与最佳实践
      代码组织与模块化
      // 使用Tree Shaking(ES6模块)
      // 只导入需要的内容
      import { debounce } from './utils.js'; // 而不是 import * as utils

      // 按需加载
      // 动态导入
      async function loadChart() {
      const { Chart } = await import('./chart-library.js');
      const chart = new Chart(data);
      }

      // 使用Web Workers处理密集计算
      // worker.js
      self.onmessage = function(e) {
      const result = heavyComputation(e.data);
      self.postMessage(result);
      };

      // 主线程
      const worker = new Worker('worker.js');
      worker.postMessage(data);
      worker.onmessage = (e) => {
      console.log('Result:', e.data);
      };
      内存管理
      // 避免内存泄漏
      function createLeak() {
      const largeArray = new Array(1000000).fill('data');

      // 错误:闭包持有外部引用
      return function() {
      console.log(largeArray.length);
      };
      }

      // 正确:及时清理
      function safeUsage() {
      const data = fetchData();
      processData(data);
      // data超出作用域后会被垃圾回收
      }

      // 事件监听器清理
      class Component {
      constructor() {
      this.handleClick = this.handleClick.bind(this);
      document.addEventListener('click', this.handleClick);
      }

      handleClick(e) {
      // 处理点击
      }

      destroy() {
      // 必须清理!
      document.removeEventListener('click', this.handleClick);
      }
      }

      // 使用WeakMap避免循环引用
      const wm = new WeakMap();
      const obj = { name: 'test' };
      wm.set(obj, { data: 'sensitive' });

      // obj被垃圾回收时,wm中的条目也会自动清除
      性能监控
      // 使用Performance API
      function measurePerformance() {
      const start = performance.now();

      // 执行代码
      for (let i = 0; i < 1000000; i++) { // 一些计算 } const end = performance.now(); console.log(`Execution time: ${end - start}ms`); } // 监控长任务 const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
      if (entry.duration > 50) {
      console.warn('Long task detected:', entry.duration);
      }
      }
      });

      observer.observe({ entryTypes: ['longtask'] });

      // 自定义指标
      function trackMetric(name, value) {
      if (typeof gtag !== 'undefined') {
      gtag('event', name, { value });
      }
      }
      调试与错误处理
      现代调试技术
      // 使用console高级功能
      console.group('User Actions');
      console.log('Action 1: Login');
      console.log('Action 2: Fetch data');
      console.groupEnd();

      // 条件断点
      function complexLogic(x) {
      // 在浏览器开发者工具中设置条件断点:x > 100
      return x * 2;
      }

      // 使用debugger语句
      function problematicFunction() {
      debugger; // 浏览器会在这一行暂停
      // 复杂逻辑
      }

      // 性能分析
      function profileFunction() {
      console.time('operation');
      // 执行操作
      console.timeEnd('operation');
      }

      // 使用Source Maps
      // 在webpack配置中启用source maps
      // module.exports = {
      // devtool: 'source-map'
      // }
      错误处理策略
      // 全局错误处理
      window.addEventListener('error', (event) => {
      console.error('Global error:', event.error);
      // 发送到错误监控服务
      sendToMonitoring(event.error);
      });

      // Promise未处理的拒绝
      window.addEventListener('unhandledrejection', (event) => {
      console.error('Unhandled promise rejection:', event.reason);
      event.preventDefault();
      });

      // 自定义错误类型
      class ValidationError extends Error {
      constructor(message, field) {
      super(message);
      this.name = 'ValidationError';
      this.field = field;
      }
      }

      // 使用
      function validateUser(user) {
      if (!user.name) {
      throw new ValidationError('Name is required', 'name');
      }
      }

      // 错误边界(React)
      class ErrorBoundary extends React.Component {
      constructor(props) {
      super(props);
      this.state = { hasError: false, error: null };
      }

      static getDerivedStateFromError(error) {
      return { hasError: true, error };
      }

      componentDidCatch(error, errorInfo) {
      console.error('Error caught by boundary:', error, errorInfo);
      }

      render() {
      if (this.state.hasError) {
      return

      Something went wrong.

      ;
      }
      return this.props.children;
      }
      }
      总结与展望
      JavaScript作为前端开发的核心语言,其生态系统持续演进。从基础语法到现代框架,从DOM操作到异步编程,掌握这些知识将帮助你构建高效、可维护的Web应用。
      关键要点回顾
      :
      基础语法
      :理解变量作用域、数据类型、函数和面向对象编程
      DOM操作
      :高效地查询和修改DOM,使用事件委托
      异步编程
      :掌握Promise、async/await和错误处理
      ES6+特性
      :利用现代语法提高开发效率
      框架应用
      :根据项目需求选择合适的框架
      性能优化
      :关注内存管理、代码分割和性能监控
      调试技巧
      :使用现代工具快速定位和解决问题
      未来趋势
      :
      WebAssembly与JavaScript的结合
      更智能的框架和工具链
      服务端渲染(SSR)和静态生成(SSG)
      Web Components和微前端架构
      AI辅助编程
      持续学习和实践是掌握JavaScript的关键。通过构建实际项目、阅读优秀代码、参与社区讨论,你将不断提升自己的技能水平,成为一名优秀的前端开发者。