JavaScript là ngôn ngữ dựa trên prototype. Mọi đối tượng built-in (Object, Array, String, Function...) đều có thuộc tính prototype. Ta có thể thêm phương thức mới vào prototype để mở rộng chức năng cho tất cả instance. Lưu ý: Không nên ghi đè hoặc xóa phương thức gốc.
Ví dụ
Thêm phương thức alternateCase() vào String.prototype để chuyển chuỗi thành chữ hoa/thường xen kẽ:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Native Prototypes JS</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 18px; font-weight: 500; color: rebeccapurple; }
.sample { color: red; }
</style>
</head>
<body>
<h1>Prototype gốc trong JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CHUYỂN ĐỔI</button>
<h3>Nhấn nút để chuyển chuỗi sang alternateCase qua prototype</h3>
<script>
const resEle = document.querySelector(".result");
const sampleEle = document.querySelector(".sample");
const btn = document.querySelector(".Btn");
// Mở rộng String prototype
String.prototype.alternateCase = function () {
let newStr = '';
for (let i = 0; i < this.length; i++) {
newStr += i % 2 === 0 ? this[i].toUpperCase() : this[i].toLowerCase();
}
return newStr;
};
const str = "HELLO WORLD";
sampleEle.textContent = str;
btn.addEventListener("click", () => {
resEle.textContent = str.alternateCase(); // "HeLlO WoRlD"
});
</script>
</body>
</html>
Kết quả
Chuỗi gốc: "HELLO WORLD". Sau khi nhấn nút: "HeLlO WoRlD".
Cảnh báo: Mở rộng native prototype có thể gây xung đột thư viện, khó debug. Nên dùng composition hoặc utility functions thay vì monkey-patching.