Programming Paradigms
Explore major programming paradigms — imperative, declarative, OOP, and functional — and 当到 use 每个.
你将学到
- 什么 programming paradigm 是 and 为什么那里是 几个
- Imperative 对比. declarative: telling computer 如何对比. 什么
- 对象-oriented programming: 封装 and 对象
- Functional programming: pure 函数 and immutability
- 如何 JavaScript supports 多个 paradigms
概念讲解
Programming Paradigms
A programming paradigm is a style or philosophy of writing code. It is a set of principles that shapes how you structure your programs, how you organize data, and how you express logic. No paradigm is universally "best" — each is a lens that makes certain problems easier to solve and certain patterns more natural to express.
Imperative vs. Declarative
The most fundamental distinction is between imperative and declarative code:
- Imperative — you describe *how* to do something, step by step. "创建循环, initialize 计数器, 检查每个元素, 更新 result." You control every step.
- Declarative — you describe *what* you want, and let the system figure out how. "Give me 所有项哪里 price > 100." You specify the result, not the process.
// Imperative: how to filter
const result = [];
for (const item of items) {
if (item.price > 100) result.push(item);
}
// Declarative: what to filter
const result = items.filter(item => item.price > 100);
Both produce the same output. The declarative version is shorter and focuses on the *what*. The imperative version gives you more control but is more verbose. JavaScript supports both styles, and most code uses a mix.
Object-Oriented Programming (OOP)
OOP organizes code around objects — bundles of data and the methods that operate on that data. The core ideas are:
- Encapsulation — objects hide their internal state and expose a controlled interface.
- Inheritance — objects can inherit properties and methods from other objects.
- Polymorphism — different objects can respond to the same message in their own way.
OOP is natural for modeling real-world entities: a 用户 object has a name, an email, and methods like 登录() and 登出(). It shines in GUI applications, game engines, and large systems with many interacting entities.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() { return `Hello, I 是 ${这个.name}`; }
}
const ada = new User("Ada", "[email protected]");
ada.greet(); // "Hello, I 是 Ada"
Functional Programming (FP)
FP organizes code around pure functions — functions that always return the same output for the same input and have no side effects. The core ideas are:
- Pure functions — no mutation, no side effects, deterministic output.
- Immutability — data is never changed; you create new data instead.
- First-class functions — functions are values that can be passed and returned.
FP is natural for data transformation, concurrent processing, and UI rendering. It shines in reactive systems, data pipelines, and anywhere predictability is critical.
// Pure function: same input → same output, no side effects
const double = (n) => n * 2;
const numbers = [1, 2, 3];
const doubled = numbers.map(double); // [2, 4, 6] — original unchanged
JavaScript's Multi-Paradigm Nature
JavaScript is a multi-paradigm language — it supports imperative, OOP, and functional styles. You can write a class-based OOP program, a functional pipeline of pure functions, or a mix of both. This flexibility is powerful but requires discipline: choose a paradigm for each module and be consistent within it.
Choosing a Paradigm
- Use OOP when you have entities with state and behavior (UI components, game objects, domain models).
- Use FP when you transform data through a pipeline (data processing, event handling, calculations).
- Use declarative style by default — it is shorter and less error-prone.
- Drop to imperative when you need fine-grained control or performance.
The best developers are paradigm-fluent: they know all the styles and choose the right one for each situation. You do not need to pick a side — you need to understand the trade-offs.
示例代码
// --- OOP approach: a shopping cart class ---
class ShoppingCart {
constructor() { this.items = []; }
add(item) { this.items.push(item); }
total() {
return this.items.reduce((sum, i) => sum + i.price, 0);
}
}
const cart = new ShoppingCart();
cart.add({ name: "Book", price: 15 });
cart.add({ name: "Pen", price: 2 });
console.log("OOP total:", cart.total()); // 17
// --- Functional approach: pure functions, immutable data ---
const addItem = (cart, item) => [...cart, item];
const calculateTotal = (cart) =>
cart.reduce((sum, i) => sum + i.price, 0);
let functionalCart = [];
functionalCart = addItem(functionalCart, { name: "Book", price: 15 });
functionalCart = addItem(functionalCart, { name: "Pen", price: 2 });
console.log("FP total:", calculateTotal(functionalCart)); // 17
// --- Declarative vs. Imperative: find expensive items ---
const allItems = [
{ name: "Laptop", price: 999 },
{ name: "Mouse", price: 25 },
{ name: "Keyboard", price: 80 },
];
// Declarative (functional style):
const expensive = allItems.filter(item => item.price > 50);
// Imperative (procedural style):
const expensiveManual = [];
for (const item of allItems) {
if (item.price > 50) expensiveManual.push(item);
}
console.log(expensive); // [{ Laptop }, { Keyboard }]
console.log(expensiveManual); // same result, more code
OOP version encapsulates cart 状态 in 类. FP version uses pure 函数 and 不可变数组 (spread 创建新 数组每个时间). 两者都 produce 相同 result. declarative 筛选是 shorter than imperative 循环.
动手试一试
- JSON Formatter
格式化是 pure 函数: 相同 JSON 输入总是 produces 相同格式化输出, 使用否 边副作用. functional programming 示例.
- Code Minifier
Minification 是 transformation 流水线 — declarative, functional 方法到 处理 code. 输入 in, smaller 输出 out.
常见错误
错误写法
Mixing paradigms inconsistently 在内相同模块.
正确做法
选择主要 paradigm for 每个模块 and stick 使用它. Mixing OOP 类使用 functional 流水线 and imperative 循环 in one file 创建 confusion. Consistency 在内模块是 更多重要 than 哪个 paradigm 你选择.
错误写法
编写 OOP 使用否 封装 — 一切公共, 否方法.
正确做法
如果你 use 类, use 它们 for 它们的 purpose: encapsulate 状态 and provide 方法. 如果你的类 是只是 bag 的公共属性, plain 对象 or 函数会 是 simpler. OOP 不使用封装是 只是 structured 数据.
错误写法
编写 'functional' code 那个 still mutates shared 状态.
正确做法
Functional programming 平均值 pure 函数 and immutability. 如果你的函数修改外部变量, 编写到 file, or 更改它的输入, 它是 不 pure — 它是 imperative code in functional costume.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for 类语法, arrow 函数, and 数组方法 used 跨越 paradigms.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。