将方法添加到 Javascript 原型
以下是将方法添加到 JavaScript 原型中的代码 −
示例
<!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>Adding methods to Javascript Prototypes</h1> <div class="result"></div> <br /> <button class="Btn">Click Here</button> <h3>Click on the above button to call the methods of person1 and person2 object</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function personConstructor(fName, lName, birthYear) { this.fName = fName; this.lName = lName; this.birthYear = birthYear; } personConstructor.prototype.welcome = function () { return "Welcome " + this.fName + " " + this.lName; }; personConstructor.prototype.calcAge = function () { return "Your age = " + (new Date().getFullYear() - this.birthYear); }; let person1 = new personConstructor("Rohan", "Sharma", 1995); let person2 = new personConstructor("Shawn", "Smith", 1992); BtnEle.addEventListener("click", () => { resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>"; resEle.innerHTML += "person1.calcAge() = " + person1.calcAge() + "<br>"; resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>"; resEle.innerHTML += "person2.calcAge() = " + person2.calcAge() + "<br>"; }); </script> </body> </html>
输出
单击“在此处单击”按钮 −
广告