Inheritance in JavaScript with example

JavascriptWeb DevelopmentObject Oriented Programming

JavaScript is an object-based language based on prototypes. Inheritance is implemented in JavaScript using the prototype object.

Following is the code to implement Inheritance in JavaScript −

Example

 Live Demo

<!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: 18;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Inheritance</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to call the welcome method inherited by person1 and person2 object
</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   function Person(name, age, city) {
      this.name = name;
      this.age = age;
      this.city = city;
   }
   Person.prototype.welcome = function () {
      resEle.innerHTML +=
      " Welcome "+this.name+" age: "+this.age +" city: "+this.city+"<br>";
   };
   BtnEle.addEventListener("click", () => {
      let person1 = new Person("Rohan", 22, "Delhi");
      person1.welcome();
      let person2 = new Person("Shawn", 19, "England");
      person2.welcome();
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −


raja
Published on 16-Jul-2020 12:53:31
Advertisements