目录

一、JavaScript概述与发展历程

1.1 什么是JavaScript

1.2 发展历程

1.3 JavaScript运行环境

二、JavaScript核心语法

2.1 变量与数据类型

2.2 运算符

2.3 控制流程

三、函数与作用域

3.1 函数定义

3.2 参数处理

3.3 作用域与闭包

四、对象与面向对象编程

4.1 对象创建

4.2 原型与继承

4.3 对象操作

五、数组与迭代

5.1 数组创建与操作

5.2 数组迭代方法

六、异步编程

6.1 回调函数

6.2 Promise

6.3 async/await

七、模块化

7.1 ES6模块

7.2 动态导入

八、现代JavaScript特性(ES6+)

8.1 解构赋值

8.2 扩展语法

8.3 模板字符串

8.4 新数据结构

九、错误处理

9.1 try...catch语句

9.2 自定义错误

十、DOM操作

10.1 元素选择

10.2 元素操作

10.3 事件处理

十一、现代JavaScript开发

11.1 ES6+新特性

11.2 Promise增强

十二、性能优化与最佳实践

12.1 性能优化

12.2 内存管理

十三、JavaScript生态

13.1 包管理

13.2 常用工具库

十四、TypeScript简介

十五、未来发展趋势

15.1 新提案

15.2 WebAssembly集成

总结


一、JavaScript概述与发展历程

1.1 什么是JavaScript

        JavaScript是一种高级的、解释型的编程语言,最初由Brendan Eich于1995年创造。作为Web的三大核心技术之一(与HTML、CSS并列),JavaScript实现了网页的动态交互功能,现已成为全栈开发的重要语言。

1.2 发展历程

  • 1995年:诞生于网景公司,原名Mocha,后改名为LiveScript,最终定为JavaScript

  • 1997年:ECMAScript 1标准发布,由ECMA国际组织标准化

  • 2009年:Node.js发布,JavaScript进入服务端开发领域

  • 2015年:ES6(ES2015)发布,带来革命性更新

  • 至今:每年发布新版本,持续演进

1.3 JavaScript运行环境

  • 浏览器环境:Chrome V8、Firefox SpiderMonkey、Safari JavaScriptCore

  • 服务器环境:Node.js、Deno、Bun

  • 移动端:React Native、NativeScript

  • 桌面端:Electron、NW.js

附(转载菜鸟教程):JavaScript 教程 | 菜鸟教程

二、JavaScript核心语法

2.1 变量与数据类型

// 变量声明
var oldWay = "不推荐使用";      // 函数作用域,存在变量提升
let modernWay = "推荐使用";    // 块级作用域,可重新赋值
const constantValue = "常量";  // 块级作用域,不可重新赋值

// 数据类型
const primitiveTypes = {
  string: "文本",              // 字符串
  number: 42,                  // 数字(整数和浮点数)
  bigint: 9007199254740991n,  // 大整数
  boolean: true,               // 布尔值
  undefined: undefined,        // 未定义
  null: null,                  // 空值
  symbol: Symbol("unique")     // 唯一标识符
};

// 引用类型
const referenceTypes = {
  object: { key: "value" },    // 对象
  array: [1, 2, 3],            // 数组
  function: function() {},     // 函数
  date: new Date(),            // 日期
  regexp: /pattern/g           // 正则表达式
};

2.2 运算符

// 算术运算符
let a = 10 + 5;    // 加
let b = 10 - 5;    // 减
let c = 10 * 5;    // 乘
let d = 10 / 5;    // 除
let e = 10 % 3;    // 取余
let f = 10 ** 2;   // 指数
let g = ++a;       // 自增
let h = --b;       // 自减

// 赋值运算符
let x = 10;
x += 5;   // x = x + 5
x -= 3;   // x = x - 3
x *= 2;   // x = x * 2
x /= 4;   // x = x / 4
x %= 3;   // x = x % 3

// 比较运算符
10 == "10"     // true,值相等(类型转换)
10 === "10"    // false,严格相等(值和类型)
10 != "10"     // false
10 !== "10"    // true
5 > 3          // true
5 < 3          // false
5 >= 5         // true
5 <= 5         // true

// 逻辑运算符
true && false    // false,与
true || false    // true,或
!true            // false,非

2.3 控制流程

// 条件语句
if (condition) {
  // 条件为真时执行
} else if (anotherCondition) {
  // 其他条件
} else {
  // 其他情况
}

// 三元运算符
const result = condition ? "真" : "假";

// switch语句
switch (value) {
  case 1:
    console.log("情况1");
    break;
  case 2:
    console.log("情况2");
    break;
  default:
    console.log("默认情况");
}

// 循环语句
for (let i = 0; i < 10; i++) {
  console.log(i);
}

let j = 0;
while (j < 10) {
  console.log(j);
  j++;
}

let k = 0;
do {
  console.log(k);
  k++;
} while (k < 10);

// for...of循环(遍历可迭代对象)
for (const item of array) {
  console.log(item);
}

// for...in循环(遍历对象属性)
for (const key in object) {
  console.log(key, object[key]);
}

三、函数与作用域

3.1 函数定义

// 函数声明(会提升)
function add(a, b) {
  return a + b;
}

// 函数表达式
const multiply = function(a, b) {
  return a * b;
};

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

// 立即执行函数表达式(IIFE)
(function() {
  console.log("立即执行");
})();

// 生成器函数
function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

3.2 参数处理

// 默认参数
function greet(name = "访客") {
  return `你好, ${name}!`;
}

// 剩余参数
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

// 参数解构
function getUserInfo({ name, age, city = "未知" }) {
  return `${name},${age}岁,来自${city}`;
}

3.3 作用域与闭包

// 作用域链
let globalVar = "全局变量";

function outer() {
  let outerVar = "外部变量";
  
  function inner() {
    let innerVar = "内部变量";
    console.log(globalVar);  // 可以访问
    console.log(outerVar);   // 可以访问
    console.log(innerVar);   // 可以访问
  }
  
  inner();
  // console.log(innerVar); // 错误:无法访问内部变量
}

// 闭包
function createCounter() {
  let count = 0;
  
  return {
    increment: function() {
      count++;
      return count;
    },
    decrement: function() {
      count--;
      return count;
    },
    getCount: function() {
      return count;
    }
  };
}

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

四、对象与面向对象编程

4.1 对象创建

// 对象字面量
const person = {
  name: "张三",
  age: 25,
  greet() {
    return `你好,我是${this.name}`;
  }
};

// 构造函数
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  return `你好,我是${this.name}`;
};

const john = new Person("张三", 25);

// 类(ES6)
class PersonClass {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  // 实例方法
  greet() {
    return `你好,我是${this.name}`;
  }
  
  // 静态方法
  static createAnonymous() {
    return new PersonClass("匿名", 0);
  }
  
  // Getter/Setter
  get info() {
    return `${this.name},${this.age}岁`;
  }
  
  set info(value) {
    const [name, age] = value.split(",");
    this.name = name;
    this.age = parseInt(age);
  }
}

4.2 原型与继承

// 原型链继承
function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(`${this.name} 发出声音`);
};

function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
  console.log("汪汪!");
};

// 类继承(ES6)
class AnimalClass {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} 发出声音`);
  }
}

class DogClass extends AnimalClass {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
  
  bark() {
    console.log("汪汪!");
  }
  
  // 重写父类方法
  speak() {
    super.speak();  // 调用父类方法
    this.bark();
  }
}

4.3 对象操作

const user = {
  name: "张三",
  age: 25,
  email: "zhangsan@example.com"
};

// 属性访问
console.log(user.name);        // 点符号
console.log(user["age"]);      // 方括号

// 属性描述符
const descriptor = Object.getOwnPropertyDescriptor(user, "name");
console.log(descriptor);
/*
{
  value: "张三",
  writable: true,
  enumerable: true,
  configurable: true
}
*/

// 定义属性
Object.defineProperty(user, "id", {
  value: 1,
  writable: false,      // 不可写
  enumerable: true,     // 可枚举
  configurable: false   // 不可配置
});

// 对象方法
const keys = Object.keys(user);        // ["name", "age", "email", "id"]
const values = Object.values(user);    // ["张三", 25, "zhangsan@example.com", 1]
const entries = Object.entries(user);  // [["name", "张三"], ...]

const clone = Object.assign({}, user);  // 浅拷贝
const merged = Object.assign({}, user, { city: "北京" });

const frozen = Object.freeze(user);     // 冻结对象
const sealed = Object.seal(user);       // 密封对象

五、数组与迭代

5.1 数组创建与操作

// 数组创建
const arr1 = [1, 2, 3];                     // 字面量
const arr2 = new Array(3);                 // 构造函数
const arr3 = Array.from("hello");          // ["h", "e", "l", "l", "o"]
const arr4 = Array.of(1, 2, 3);           // [1, 2, 3]

// 基本操作
const fruits = ["苹果", "香蕉", "橙子"];
fruits.push("葡萄");                       // 末尾添加
const last = fruits.pop();                 // 末尾移除
fruits.unshift("草莓");                     // 开头添加
const first = fruits.shift();              // 开头移除
fruits.splice(1, 1, "芒果");               // 删除并添加

5.2 数组迭代方法

const numbers = [1, 2, 3, 4, 5];

// forEach - 遍历
numbers.forEach((num, index) => {
  console.log(`索引${index}: ${num}`);
});

// map - 映射新数组
const doubled = numbers.map(num => num * 2);

// filter - 过滤
const evens = numbers.filter(num => num % 2 === 0);

// reduce - 累积
const sum = numbers.reduce((total, num) => total + num, 0);

// find - 查找元素
const firstEven = numbers.find(num => num % 2 === 0);

// findIndex - 查找索引
const firstEvenIndex = numbers.findIndex(num => num % 2 === 0);

// some - 是否有符合条件的
const hasEven = numbers.some(num => num % 2 === 0);

// every - 是否所有都符合条件
const allPositive = numbers.every(num => num > 0);

// flat - 扁平化
const nested = [1, [2, [3, [4]]]];
const flat = nested.flat(3);  // [1, 2, 3, 4]

// flatMap - 映射后扁平化
const sentences = ["Hello world", "Good morning"];
const words = sentences.flatMap(sentence => sentence.split(" "));

六、异步编程

6.1 回调函数

// 传统回调
function fetchData(callback) {
  setTimeout(() => {
    const data = { id: 1, name: "张三" };
    callback(null, data);
  }, 1000);
}

fetchData((error, data) => {
  if (error) {
    console.error("错误:", error);
  } else {
    console.log("数据:", data);
  }
});

// 回调地狱
getUser(userId, (userError, user) => {
  if (userError) {
    handleError(userError);
  } else {
    getPosts(user.id, (postsError, posts) => {
      if (postsError) {
        handleError(postsError);
      } else {
        getComments(posts[0].id, (commentsError, comments) => {
          if (commentsError) {
            handleError(commentsError);
          } else {
            // 处理数据...
          }
        });
      }
    });
  }
});

6.2 Promise

// 创建Promise
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = Math.random() > 0.5;
    if (success) {
      resolve("操作成功!");
    } else {
      reject(new Error("操作失败"));
    }
  }, 1000);
});

// 使用Promise
promise
  .then(result => {
    console.log(result);
    return "链式调用";
  })
  .then(value => {
    console.log(value);
  })
  .catch(error => {
    console.error("捕获错误:", error);
  })
  .finally(() => {
    console.log("无论成功失败都会执行");
  });

// Promise静态方法
Promise.resolve(42);        // 创建已解决的Promise
Promise.reject(new Error()); // 创建已拒绝的Promise

// Promise.all - 全部成功
Promise.all([
  fetch("/api/user"),
  fetch("/api/posts"),
  fetch("/api/comments")
])
  .then(([user, posts, comments]) => {
    // 所有请求都成功
  })
  .catch(error => {
    // 任一请求失败
  });

// Promise.race - 竞速
Promise.race([
  fetchWithTimeout("/api/data", 5000),
  timeout(3000)  // 3秒超时
]);

// Promise.allSettled - 所有都完成
Promise.allSettled([
  fetch("/api/success"),
  fetch("/api/error")
])
  .then(results => {
    results.forEach(result => {
      if (result.status === "fulfilled") {
        console.log("成功:", result.value);
      } else {
        console.log("失败:", result.reason);
      }
    });
  });

6.3 async/await

// async函数
async function fetchUserData(userId) {
  try {
    // 等待Promise完成
    const user = await fetch(`/api/users/${userId}`);
    const posts = await fetch(`/api/users/${userId}/posts`);
    const comments = await fetch(`/api/users/${userId}/comments`);
    
    return { user, posts, comments };
  } catch (error) {
    console.error("获取数据失败:", error);
    throw error;
  }
}

// 并行请求
async function fetchAllData(userId) {
  try {
    const [user, posts, comments] = await Promise.all([
      fetch(`/api/users/${userId}`),
      fetch(`/api/users/${userId}/posts`),
      fetch(`/api/users/${userId}/comments`)
    ]);
    
    return { user, posts, comments };
  } catch (error) {
    console.error("获取数据失败:", error);
    throw error;
  }
}

// 立即执行async函数
(async () => {
  try {
    const data = await fetchUserData(1);
    console.log(data);
  } catch (error) {
    console.error(error);
  }
})();

七、模块化

7.1 ES6模块

// math.js - 导出模块
export const PI = 3.14159;

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

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

// 默认导出
export default class Calculator {
  constructor() {
    this.version = "1.0";
  }
  
  calculate(expression) {
    return eval(expression);
  }
}

// 重命名导出
export { add as sum, multiply as product };

// app.js - 导入模块
import Calculator, { PI, add, multiply } from "./math.js";
import { sum as addNumbers } from "./math.js";
import * as MathUtils from "./math.js";  // 全部导入

console.log(PI);  // 3.14159
console.log(add(2, 3));  // 5

const calc = new Calculator();
console.log(calc.calculate("2 + 2"));  // 4

7.2 动态导入

// 动态导入
async function loadModule(moduleName) {
  try {
    const module = await import(`./modules/${moduleName}.js`);
    module.initialize();
  } catch (error) {
    console.error(`加载模块 ${moduleName} 失败:`, error);
  }
}

// 条件导入
if (userNeedsChart) {
  const chartModule = await import("./charting.js");
  chartModule.renderChart(data);
}

八、现代JavaScript特性(ES6+)

8.1 解构赋值

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

// 对象解构
const person = { name: "张三", age: 25, city: "北京" };
const { name, age, country = "中国" } = person;
console.log(name);    // 张三
console.log(country); // 中国

// 函数参数解构
function printUser({ name, age, city = "未知" }) {
  console.log(`${name},${age}岁,来自${city}`);
}

// 嵌套解构
const data = {
  user: {
    name: "张三",
    details: { age: 25, email: "test@example.com" }
  }
};
const { user: { name: userName, details: { age: userAge } } } = data;

8.2 扩展语法

// 数组扩展
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 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 };  // { a: 1, b: 3, c: 4 }

// 函数参数扩展
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5));  // 15

8.3 模板字符串

const name = "张三";
const age = 25;

// 基本用法
const greeting = `你好,我是${name},今年${age}岁。`;

// 多行字符串
const multiLine = `
  第一行
  第二行
  第三行
`;

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

const message = highlight`你好,${name}!`;

8.4 新数据结构

// Set - 唯一值集合
const uniqueNumbers = new Set([1, 2, 2, 3, 3, 3]);
uniqueNumbers.add(4);       // 添加元素
uniqueNumbers.delete(1);    // 删除元素
uniqueNumbers.has(2);       // 检查存在
uniqueNumbers.size;         // 集合大小
uniqueNumbers.clear();      // 清空集合

// Map - 键值对集合
const userMap = new Map();
userMap.set("张三", 25);
userMap.set("李四", 30);
userMap.get("张三");        // 25
userMap.has("李四");        // true
userMap.delete("张三");     // 删除
userMap.size;              // 大小

// WeakSet/WeakMap - 弱引用集合
const weakSet = new WeakSet();
const weakMap = new WeakMap();
const obj = {};
weakSet.add(obj);
weakMap.set(obj, "值");

九、错误处理

9.1 try...catch语句

try {
  // 可能出错的代码
  const result = riskyOperation();
  console.log("结果:", result);
} catch (error) {
  // 处理错误
  console.error("发生错误:", error.message);
  console.error("错误堆栈:", error.stack);
  
  // 重新抛出错误
  if (error instanceof TypeError) {
    console.error("类型错误");
  } else {
    throw error;  // 重新抛出
  }
} finally {
  // 无论是否出错都会执行
  console.log("清理工作...");
}

9.2 自定义错误

// 自定义错误类
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
    this.timestamp = new Date().toISOString();
  }
  
  toJSON() {
    return {
      name: this.name,
      message: this.message,
      field: this.field,
      timestamp: this.timestamp
    };
  }
}

// 使用自定义错误
function validateUser(user) {
  if (!user.name) {
    throw new ValidationError("用户名不能为空", "name");
  }
  if (user.age < 0) {
    throw new ValidationError("年龄不能为负数", "age");
  }
  return true;
}

try {
  validateUser({ name: "", age: -1 });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`字段 ${error.field} 验证失败: ${error.message}`);
  } else {
    console.error("未知错误:", error);
  }
}

十、DOM操作

10.1 元素选择

// 获取元素
const element = document.getElementById("myId");
const elements = document.getElementsByClassName("myClass");
const tags = document.getElementsByTagName("div");

// 现代选择器
const el = document.querySelector("#myId .myClass");  // 单个元素
const all = document.querySelectorAll(".myClass");     // 所有匹配元素

// 遍历元素
document.querySelectorAll(".item").forEach((item, index) => {
  console.log(`元素 ${index}:`, item);
});

10.2 元素操作

// 创建元素
const newDiv = document.createElement("div");
newDiv.id = "newElement";
newDiv.className = "container";
newDiv.textContent = "Hello World";

// 修改属性
newDiv.setAttribute("data-id", "123");
const id = newDiv.getAttribute("data-id");
newDiv.removeAttribute("data-id");

// 样式操作
newDiv.style.backgroundColor = "blue";
newDiv.style.fontSize = "16px";
newDiv.classList.add("active");
newDiv.classList.remove("inactive");
newDiv.classList.toggle("visible");

// 添加/移除元素
const parent = document.getElementById("parent");
parent.appendChild(newDiv);
parent.insertBefore(newDiv, parent.firstChild);
parent.removeChild(newDiv);

// 替换元素
const oldElement = document.getElementById("old");
const newElement = document.createElement("div");
parent.replaceChild(newElement, oldElement);

10.3 事件处理

// 事件监听
const button = document.getElementById("myButton");

function handleClick(event) {
  console.log("按钮被点击了", event);
  console.log("事件目标:", event.target);
  console.log("当前目标:", event.currentTarget);
  console.log("鼠标位置:", event.clientX, event.clientY);
  
  // 阻止默认行为
  event.preventDefault();
  
  // 停止事件传播
  event.stopPropagation();
}

// 添加事件监听
button.addEventListener("click", handleClick);

// 移除事件监听
button.removeEventListener("click", handleClick);

// 事件委托
document.getElementById("list").addEventListener("click", (event) => {
  if (event.target.classList.contains("list-item")) {
    console.log("点击了列表项:", event.target.textContent);
  }
});

// 自定义事件
const customEvent = new CustomEvent("myEvent", {
  detail: { message: "自定义事件数据" },
  bubbles: true,
  cancelable: true
});

button.dispatchEvent(customEvent);

十一、现代JavaScript开发

11.1 ES6+新特性

// 可选链操作符
const userName = user?.profile?.name ?? "匿名";

// 空值合并运算符
const displayName = username ?? "匿名用户";
const score = inputScore || 0;  // 0会被视为false
const betterScore = inputScore ?? 0;  // 只有null/undefined时使用默认值

// 可选catch绑定
try {
  // 可能出错的代码
} catch {  // 不需要error参数
  console.log("出错了,但不需要错误详情");
}

// 全局This
const globalObject = (() => {
  if (typeof globalThis !== "undefined") return globalThis;
  if (typeof self !== "undefined") return self;
  if (typeof window !== "undefined") return window;
  if (typeof global !== "undefined") return global;
  return Function('return this')();
})();

// 私有字段和方法
class Counter {
  #count = 0;  // 私有字段
  
  #increment() {  // 私有方法
    this.#count++;
  }
  
  get value() {
    return this.#count;
  }
  
  tick() {
    this.#increment();
  }
}

11.2 Promise增强

// Promise.allSettled
const promises = [
  Promise.resolve(1),
  Promise.reject(new Error("失败")),
  Promise.resolve(3)
];

Promise.allSettled(promises).then(results => {
  results.forEach(result => {
    if (result.status === "fulfilled") {
      console.log("成功:", result.value);
    } else {
      console.log("失败:", result.reason);
    }
  });
});

// Promise.any
const fastPromise = Promise.any([
  fetch("/api/slow"),
  fetch("/api/fast"),
  fetch("/api/medium")
]);

fastPromise.then(result => {
  console.log("最快的响应:", result);
}).catch(error => {
  console.log("所有请求都失败了");
});

// 顶层await
const response = await fetch("/api/data");
const data = await response.json();

十二、性能优化与最佳实践

12.1 性能优化

// 防抖
function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// 节流
function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 事件监听优化
const items = document.querySelectorAll('.item');
const optimizedHandler = debounce((event) => {
  // 处理事件
}, 300);

items.forEach(item => {
  item.addEventListener('input', optimizedHandler);
});

// 虚拟滚动
function renderVisibleItems(items, containerHeight, itemHeight) {
  const visibleCount = Math.ceil(containerHeight / itemHeight);
  const startIndex = Math.floor(scrollTop / itemHeight);
  const endIndex = startIndex + visibleCount;
  
  return items.slice(startIndex, endIndex);
}

12.2 内存管理

// 避免内存泄漏
function createLargeObject() {
  const largeArray = new Array(1000000).fill("data");
  return function process() {
    // 错误:闭包持有largeArray引用
    console.log(largeArray.length);
  };
}

// 正确做法
function createOptimizedObject() {
  const data = { largeArray: new Array(1000000).fill("data") };
  
  return {
    process: function() {
      // 只使用需要的数据
      const length = data.largeArray.length;
      console.log(length);
    },
    cleanup: function() {
      // 显式清理
      data.largeArray = null;
    }
  };
}

// 定时器清理
const intervalId = setInterval(() => {
  console.log("执行中...");
}, 1000);

// 需要时清理
clearInterval(intervalId);

// 事件监听器清理
const button = document.getElementById("myButton");
const handler = () => console.log("点击");

button.addEventListener("click", handler);
// 需要时移除
button.removeEventListener("click", handler);

十三、JavaScript生态

13.1 包管理

// package.json示例
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "项目描述",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest",
    "build": "webpack --mode production"
  },
  "dependencies": {
    "express": "^4.18.0",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "jest": "^29.0.0",
    "webpack": "^5.74.0"
  }
}

13.2 常用工具库

// Lodash - 实用函数库
const _ = require('lodash');

_.chunk(['a', 'b', 'c', 'd'], 2);  // [['a', 'b'], ['c', 'd']]
_.debounce(search, 300);
_.cloneDeep(object);

// Date-fns - 日期处理
const { format, differenceInDays, addDays } = require('date-fns');

format(new Date(), 'yyyy-MM-dd');
differenceInDays(new Date(2024, 0, 1), new Date(2023, 0, 1));
addDays(new Date(), 7);

// Axios - HTTP客户端
const axios = require('axios');

axios.get('/api/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

十四、TypeScript简介

// 类型注解
let name: string = "张三";
let age: number = 25;
let isStudent: boolean = true;
let hobbies: string[] = ["篮球", "音乐"];
let person: { name: string; age: number } = { name: "张三", age: 25 };

// 接口
interface User {
  id: number;
  name: string;
  email?: string;  // 可选属性
  readonly createdAt: Date;  // 只读属性
}

// 泛型
function identity<T>(arg: T): T {
  return arg;
}

// 类
class Person {
  constructor(public name: string, private age: number) {}
  
  greet(): string {
    return `你好,我是${this.name}`;
  }
}

// 类型守卫
function isString(value: any): value is string {
  return typeof value === "string";
}

十五、未来发展趋势

15.1 新提案

  • Top-level await​ - 顶层await

  • Temporal​ - 更好的日期时间API

  • Record & Tuple​ - 不可变数据结构

  • Decorators​ - 装饰器

  • Pipeline Operator​ - 管道操作符

  • Pattern Matching​ - 模式匹配

15.2 WebAssembly集成

// 加载WebAssembly模块
const importObject = {
  imports: {
    imported_func: arg => console.log(arg)
  }
};

WebAssembly.instantiateStreaming(fetch("module.wasm"), importObject)
  .then(obj => {
    // 调用Wasm函数
    obj.instance.exports.exported_func();
  });

总结

        JavaScript已经从简单的浏览器脚本语言发展成为功能强大的全栈开发语言。通过不断演进的语言特性、丰富的生态系统和强大的工具链,JavaScript能够应对从简单的网页交互到复杂的服务器应用等各种开发场景。

        掌握JavaScript需要理解其核心概念(如作用域、闭包、原型链、异步编程),熟悉现代语法特性(如ES6+),了解性能优化技巧,并能够运用各种工具和框架解决实际问题。随着Web技术的持续发展,JavaScript将继续演进,为开发者提供更强大、更高效的开发体验。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐