JavaScript 体系
一、语言基础
-
数据类型
-
原始类型:
number、string、boolean、null、undefined、symbol、bigintlet age = 25; // number let name = "Alice"; // string let isStudent = true; // boolean let empty = null; // null → typeof 返回 'object'(历史遗留) let notDefined; // undefined let id = Symbol("id"); // symbol let bigNum = 100n; // bigint -
对象类型:
object(含数组、函数等)let person = { name: "Bob" }; // object let nums = [1, 2, 3]; // object (数组是特殊对象) function greet() { } // function → typeof 返回 'function'
-
-
变量声明
-
var:函数作用域(存在变量提升) -
let/const:块级作用域(const声明常量)if (true) { var x = 10; // 函数作用域,外部可访问 let y = 20; // 块级作用域,外部不可访问 } console.log(x); // 10 console.log(y); // ReferenceError
-
二、函数系统
-
定义与作用域
-
函数声明:存在提升(可在定义前调用)
-
箭头函数:无自己的
this,继承父级作用域// 函数表达式 const multiply = (a, b) => a * b; // 闭包示例 function counter() { let count = 0; return () => ++count; // 闭包保留对 count 的引用 } const myCounter = counter(); myCounter(); // 1
-
-
高阶函数
-
接收函数作为参数或返回函数:
// map 高阶函数 const doubled = [1, 2, 3].map(num => num * 2); // [2, 4, 6]
-
三、面向对象
-
原型继承
-
通过原型链实现属性共享:
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(`${this.name} makes a noise`); }; const dog = new Animal("Rex"); dog.speak(); // Rex makes a noise
-
-
ES6 类语法
-
更接近传统面向对象:
class Person { #privateField; // 私有字段 constructor(name) { this.name = name; } static createAnonymous() { return new Person("Anonymous"); // 静态方法 } } const user = Person.createAnonymous();
-
四、异步编程
-
事件循环模型
-
宏任务(
setTimeout)、微任务(Promise.then):console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); // 输出: Start → End → Promise → Timeout
-
-
Async/Await
-
用同步写法处理异步:
async function fetchData() { try { const res = await fetch("https://api.example.com/data"); return res.json(); } catch (err) { console.error("Fetch failed:", err); } }
-
五、现代 ES6+ 特性
-
解构与扩展运算符
// 对象解构 const { name, age } = person; // 数组展开 const newArr = [...oldArr, "newItem"]; -
可选链与空值合并
const email = user?.profile?.email ?? "default@email.com"; -
2025 新特性
-
管道操作符(提案):
value |> fn1 |> fn2 -
顶层 Await:模块中直接使用
await// 动态导入 + 顶层 await const data = await import("./api.js");
-
六、错误处理与调试
-
Try/Catch
try { JSON.parse("invalid json"); } catch (e) { console.error("Parsing error:", e.message); } -
自定义错误
class AuthError extends Error { constructor(message) { super(message); this.name = "AuthError"; } }
七、模块化
-
ES Modules
// math.js export const add = (a, b) => a + b; // main.js import { add } from "./math.js"; console.log(add(2, 3)); // 5
八、2025 前沿概念
-
Temporal API
-
替代
Date对象的日期处理方案:const now = Temporal.Now.instant(); // 精确时间戳
-
-
Records & Tuples(提案)
-
不可变数据结构:
const point = #[x: 1, y: 2]; // Record const coords = #[1, 2, 3]; // Tuple
-