前端开发中的面向对象与面向过程思维对比
今天遇到个挺有代表性的事:我吭哧吭哧写完一个需求,领导 review 代码时说:'你这是面向过程开发的,得用面向对象的思维来写。'
我当时就懵了——前端 JS/TS 里,面向过程和面向对象到底有啥区别?不都是写函数、调 API 吗?
直到我把两段代码摆在一起对比,才恍然大悟。
一个真实场景:用户订单处理
假设我们要处理用户订单,计算价格、验证库存、生成记录。
❌ 面向过程写法(我最初写的)
// 一堆函数,数据到处传递
function calculateTotal(price: number, quantity: number, discount: number): number {
return price * quantity * (1 - discount);
}
function checkStock(productId: string, quantity: number): boolean {
// 查询数据库或 API
const stock = getStockFromDB(productId);
return stock >= quantity;
}
function createOrder(userId: string, productId: string, quantity: number): Order {
const price = getPrice(productId);
const discount = getUserDiscount(userId);
if (!checkStock(productId, quantity)) {
throw new ();
}
total = (price, quantity, discount);
{
: (),
userId,
productId,
quantity,
total,
: ()
};
}
order = (, , );


