Share methods in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Methods can be shared by attaching them to the prototype property of the object. These methods will be shared among all the instances of the object.

Following is the code for sharing methods in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
<h1>Shared methods in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to the call the displayInfo method of student1 and student2 object</h3>
   let resEle = document.querySelector(".result");
   function Student(name, age, standard) { = name;
      this.age = age;
      this.standard = standard;
   Student.prototype.displayInfo = function () {
      return `${} 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();


On clicking the ‘CLICK HERE’ button −

Published on 20-Jul-2020 07:41:57