मेथड्स को ऑब्जेक्ट की प्रोटोटाइप प्रॉपर्टी से जोड़कर शेयर किया जा सकता है। ये मेथड्स ऑब्जेक्ट के सभी इंस्टेंसेज के बीच शेयर किए जाएंगे।
जावास्क्रिप्ट में मेथड्स शेयर करने का कोड निम्नलिखित है -
उदाहरण
<!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>जावास्क्रिप्ट में शेयर्ड मेथड्स</h1> <div class="result"></div> <button class="Btn">यहाँ क्लिक करें</button> <h3>student1 और student2 ऑब्जेक्ट के displayInfo मेथड को कॉल करने के लिए ऊपर दिए गए बटन पर क्लिक करें</h3> <script> let resEle = document.querySelector(".result"); function Student(name, age, standard) { this.name = name; this.age = age; this.standard = standard; } Student.prototype.displayInfo = function () { return `${this.name} age ${this.age} : standard :${this.standard} <br>`; }; let student1 = new Student("Rohan", 17, 12); let student2 = new Student("Shawn", 16, 11); document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML = student1.displayInfo(); resEle.innerHTML += student2.displayInfo(); }); </script> </body> </html>
आउटपुट

'यहाँ क्लिक करें' बटन पर क्लिक करने पर -
