Các hàm được tạo trong JavaScript luôn có thuộc tính prototype được thêm vào bởi engine JavaScript. Thuộc tính prototype là một object chứa thuộc tính constructor mặc định. Function prototype có thể được truy cập bằng:
functionName.prototype
Khi tạo đối tượng sử dụng function constructor, thuộc tính prototype này có thể được dùng để chia sẻ phương thức hoặc thuộc tính giữa các đối tượng được tạo bởi function constructor đó.
Dưới đây là mã về function prototypes trong JavaScript:
Ví dụ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Function prototypes in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">Click Here</button> <h3>Nhấn nút trên để gọi phương thức welcome của person1 và person2</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function personConstructor(fName, lName) { this.fName = fName; this.lName = lName; } personConstructor.prototype.welcome = function () { return "Welcome " + this.fName + " " + this.lName; }; let person1 = new personConstructor("Rohan", "Sharma"); let person2 = new personConstructor("Shawn", "Smith"); BtnEle.addEventListener("click", () => { resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>"; resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>"; }); </script> </body> </html>
Kết quả

Khi nhấn nút 'Click Here':
