Trung BìnhDesign Patterns iconDesign Patterns

Prototype pattern là gì? Khi nào dùng trong JavaScript/TypeScript?

Prototype cho phép copy (clone) object hiện có mà không phụ thuộc vào class của nó — tạo object mới bằng cách sao chép prototype. JavaScript đặc biệt phù hợp vì có prototype-based inheritance tự nhiên.

Ví dụ: const config = { timeout: 3000, retries: 3 }; const apiConfig = { ...config, baseURL: '/api' } — spread operator là Shallow Prototype. Dùng khi: khởi tạo object tốn kém (DB query, file I/O) và muốn clone thay vì tạo mới; khi có nhiều preset configuration chỉ khác nhau vài thuộc tính. Chú ý Shallow vs Deep clone: Object.assign() và spread {...} chỉ shallow clone, object nested vẫn shared reference — dùng structuredClone() (ES2022) hoặc JSON.parse(JSON.stringify()) cho deep clone. Không dùng khi object có circular reference hoặc function (JSON.stringify sẽ mất).

Xem toàn bộ Design Patterns cùng filter theo level & chủ đề con.

Mở danh sách Design Patterns