Skip to content

JavaScript 学习指南(2025 版)

写在前面

新语法速览

以下是ECMAScript最新标准(截至2025年),快速了解以便查阅:

避免使用的语法

以下是历史遗留或不推荐的语法,建议使用现代替代方案:

  • var:使用letconst以避免作用域问题。
  • eval/new Function:安全性和性能问题,推荐静态代码。
  • with:易导致代码混乱,推荐显式属性访问。
  • label:复杂且不必要,推荐结构化控制流。
  • ==:非严格相等可能导致意外行为,推荐===

教材与资源

视频

教程

书籍

  • 《JavaScript权威指南(第8版)》(2024):全面深入,涵盖ES2023+。
  • 《JavaScript高级程序设计(第5版)》(2025):实用开发指南,注重现代实践。
  • 《你不知道的JavaScript(更新版)》(2023):深入语言底层机制。

扩展阅读

JavaScript生态

运行环境

  • Node.js:JavaScript的服务器端运行时,支持命令行和Web开发。
    • 版本管理:nvmfnm(更轻量)。
    • 源管理:nrm切换npm镜像。

包管理

  • npm:默认包管理工具。
  • pnpm:高效、节省磁盘空间,推荐使用。
  • Bun:2025年新兴运行时和包管理器,性能优异。
  • 常用工具:

开发工具

术语表

  • JavaScript (JS):ECMAScript的具体实现,运行于浏览器和Node.js。
  • ECMAScript (ES):JavaScript的标准规范。
    • ES6/ES2015:引入箭头函数、类、模块等。
    • ES2023+:新增记录/元组、管道操作符等(部分为提案)。
    • ESNext:最新提案和实验性特性。
  • Web API:浏览器提供的接口,如DOM、Fetch。
  • JSON:基于JS语法的轻量数据格式。
  • TypeScript (TS):带类型的JS超集。
  • JSX/TSX:React的模板语法。
  • Vanilla JS:原生JavaScript,无框架。
  • ECMA-262:ECMAScript标准文档。
  • TC39:负责ECMAScript标准的委员会。

Node.js安装与运行(Mac)

sh
# 安装Node.js(推荐使用fnm)
brew install fnm
fnm install 20  # 安装Node.js v20(2025年LTS版本)

# 安装pnpm
npm install -g pnpm

# 检查版本
node -v
pnpm -v

# 运行JS代码
node
> 1 + 1
> .exit

node script.js

# 切换Node版本
fnm use 18
fnm use 20

# 管理npm源
npm install -g nrm
nrm use taobao

JavaScript语言基础知识体系

语言特性

  • 动态类型、弱类型。
  • 基于原型的继承。
  • 函数是一等公民,支持高阶函数。
  • 单线程,基于事件循环(EventLoop)实现非阻塞。
  • 高级语言,采用即时编译(JIT)。

基本语法

  1. 语法结构

    • 分号(;)可选,推荐省略(依赖ASI机制)。
    • 注释://(单行),/* */(多行),支持JSDoc。
    • 变量:let(块级作用域),const(常量),避免var
    • 严格模式:"use strict";(强制规范代码)。
    • 示例:
      javascript
      // JSDoc示例
      /** @param {number} a */
      function add(a, b) {
        return a + b;
      }
  2. 表达式与运算符

    • 算术+, -, *, /, %, **
    • 逻辑&&, ||, !, ??(空值合并)。
    • 比较===, !==, <, >, <=, >=
    • 赋值=, +=, ||=, &&=, ??=
    • 其他?.(可选链),typeof, instanceof, in, delete
    • 示例:
      javascript
      let x = 5;
      x ??= 10; // x保持5
      console.log(x?.toString()); // "5"
  3. 控制流

    • 条件if, else, switch
    • 循环for, while, do while, for...of, for...in
    • 示例:
      javascript
      for (const item of [1, 2, 3]) {
        console.log(item); // 1, 2, 3
      }
  4. 错误处理

    • 使用try, catch, finally, throw
    • 示例:
      javascript
      try {
        throw new Error("Something went wrong");
      } catch (e) {
        console.error(e.message);
      }

运行时

  • 变量提升:仅var和函数声明提升,let/const有暂时性死区。
  • 短路求值&&||在必要时停止执行。
  • 垃圾回收:基于标记清除算法。

原始数据类型

  • number42, 3.14, NaN, Infinity
  • BigInt123n
  • string"hello", 支持模板字符串`x = ${x}`
  • booleantrue, false
  • symbolSymbol('id')
  • null/undefined
  • 示例:
    javascript
    const str = `Hello ${42}`; // "Hello 42"
    const sym = Symbol('unique');

引用类型

  1. 对象

    • 创建:{ a: 1 }
    • 访问:obj.a, obj['a']
    • API:Object.keys(), Object.assign(), Object.defineProperty()
    • 示例:
      javascript
      const obj = { get x() { return 42; } };
      console.log(obj.x); // 42
  2. 数组

    • 创建:[1, 2, 3]
    • API:.map(), .filter(), .reduce(), .flat()
    • 示例:
      javascript
      const arr = [1, 2, 3].map(x => x * 2); // [2, 4, 6]

函数

  • 声明function fn() {}, 表达式:const fn = () => {}
  • 箭头函数:无thisarguments绑定。
  • 参数:支持默认值、解构、剩余参数。
  • 示例:
    javascript
    const sum = (a, b = 0, ...rest) => a + b + rest.reduce((s, x) => s + x, 0);
    console.log(sum(1, 2, 3, 4)); // 10

  • 定义class MyClass { constructor() {} }
  • 继承extends, super
  • 私有字段#field
  • 示例:
    javascript
    class Counter {
      #count = 0;
      increment() { return ++this.#count; }
    }
    const c = new Counter();
    console.log(c.increment()); // 1

异步编程

  1. Promise

    • 创建:new Promise((resolve, reject) => {})
    • API:.then(), .catch(), Promise.all(), Promise.any()
    • 示例:
      javascript
      Promise.resolve(42).then(v => console.log(v)); // 42
  2. async/await

    • 简化Promise使用,支持顶层await(模块中)。
    • 示例:
      javascript
      async function fetchData() {
        return await Promise.resolve("data");
      }
  3. Generator

    • 定义:function* fn() { yield 1; }
    • 示例:
      javascript
      function* gen() { yield* [1, 2, 3]; }
      for (const v of gen()) console.log(v); // 1, 2, 3
  4. 事件循环

    • 微任务:Promise、async/await。
    • 宏任务:setTimeout, setInterval

模块化

  • ES模块import, export
  • 动态导入import()
  • 示例:
    javascript
    export const add = (a, b) => a + b;
    import("./module.js").then(m => console.log(m.add(1, 2)));

JavaScript代码片段

ES5基础

javascript
// 变量与类型
var x = 42; // 避免使用var
console.log(typeof x); // "number"

// 字符串操作
const str = "hello " + "world";
console.log(str.split(" ")); // ["hello", "world"]

// 数组与对象
const arr = [1, 2, 3];
const obj = { a: 1, b: function() { return this.a; } };
console.log(arr.length, obj.b()); // 3, 1

// 函数与上下文
function greet(name) { return `Hi, ${name}`; }
console.log(greet.call(null, "Alice")); // "Hi, Alice"

ES6+特性

javascript
// 块级作用域与解构
{
  const [a, ...rest] = [1, 2, 3];
  console.log(a, rest); // 1, [2, 3]
}

// 箭头函数与模板字符串
const greet = (name = "Guest") => `Hello, ${name}!`;
console.log(greet()); // "Hello, Guest!"

// 类与私有字段
class User {
  #id = 0;
  constructor(name) { this.name = name; }
  getId() { return this.#id; }
}
const user = new User("Bob");
console.log(user.getId()); // 0

ES2023+与实验性特性

javascript
// 空值合并与可选链
const data = { user: null };
console.log(data.user?.name ?? "Unknown"); // "Unknown"

// 逻辑赋值
let flag = false;
flag &&= true; // flag保持false
console.log(flag); // false

// BigInt
const big = 123456789n * 2n;
console.log(big); // 246913578n

// 记录与元组(实验性)
const tuple = #[1, 2, 3]; // 不可变
console.log(tuple[0]); // 1

总结

JavaScript在2025年继续蓬勃发展,新增特性如记录/元组和管道操作符进一步提升了语言的表达力。通过掌握基础语法、现代特性、异步编程和模块化,您可以轻松应对Web开发需求。结合最新工具和资源,立即开始实践,探索JavaScript的无限可能!

Layout Switch

Adjust the layout style of VitePress to adapt to different reading needs and screens.

Expand all
The sidebar and content area occupy the entire width of the screen.
Expand sidebar with adjustable values
Expand sidebar width and add a new slider for user to choose and customize their desired width of the maximum width of sidebar can go, but the content area width will remain the same.
Expand all with adjustable values
Expand sidebar width and add a new slider for user to choose and customize their desired width of the maximum width of sidebar can go, but the content area width will remain the same.
Original width
The original layout width of VitePress

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.

Spotlight

Highlight the line where the mouse is currently hovering in the content to optimize for users who may have reading and focusing difficulties.

ONOn
Turn on Spotlight.
OFFOff
Turn off Spotlight.