面向对象与面向过程编程

两种编程范式的区别、优缺点及 JavaScript 示例

问题

什么是面向对象编程及面向过程编程,它们的异同和优缺点?

解答

面向过程编程 (POP)

以**过程(函数)**为中心,按步骤顺序执行。数据和操作数据的函数是分离的。

// 面向过程:计算矩形面积和周长

// 数据
const width = 10;
const height = 5;

// 操作数据的函数
function calculateArea(w, h) {
  return w * h;
}

function calculatePerimeter(w, h) {
  return 2 * (w + h);
}

// 按步骤调用
const area = calculateArea(width, height);
const perimeter = calculatePerimeter(width, height);

console.log(`面积: ${area}, 周长: ${perimeter}`);

面向对象编程 (OOP)

对象为中心,将数据和操作数据的方法封装在一起。

// 面向对象:计算矩形面积和周长

class Rectangle {
  // 数据和方法封装在一起
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  calculateArea() {
    return this.width * this.height;
  }

  calculatePerimeter() {
    return 2 * (this.width + this.height);
  }
}

// 创建对象,调用方法
const rect = new Rectangle(10, 5);
console.log(`面积: ${rect.calculateArea()}, 周长: ${rect.calculatePerimeter()}`);

OOP 三大特性示例

// 1. 封装:隐藏内部实现
class BankAccount {
  #balance = 0; // 私有属性

  deposit(amount) {
    if (amount > 0) this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

// 2. 继承:复用代码
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks`);
  }
}

// 3. 多态:同一方法不同表现
const animals = [new Animal('Animal'), new Dog('Buddy')];
animals.forEach(animal => animal.speak());
// Animal makes a sound
// Buddy barks

对比

特性面向过程面向对象
核心函数/过程对象
数据与方法分离封装在一起
代码复用函数调用继承、组合
适用场景简单脚本、算法复杂系统、GUI
维护性规模大时难维护易扩展维护

优缺点

面向过程

  • ✅ 简单直观,执行效率高
  • ✅ 适合小型程序和脚本
  • ❌ 代码复用性差
  • ❌ 难以维护大型项目

面向对象

  • ✅ 代码复用性强(继承)
  • ✅ 易于维护和扩展
  • ✅ 更接近现实世界建模
  • ❌ 学习成本较高
  • ❌ 小项目可能过度设计

关键点

  • 面向过程关注”怎么做”,面向对象关注”谁来做”
  • OOP 三大特性:封装、继承、多态
  • JavaScript 支持两种范式,可混合使用
  • 简单任务用面向过程,复杂系统用面向对象
  • 现代前端框架(React、Vue)大量使用 OOP 思想