What is inheritance in JavaScript explain the all inheritance?

Asked 19-Jul-2021
Viewed 201 times

0

What is inheritance in JavaScript explain the all inheritance?    


1 Answer


0

Inheritance is an important concept in object-oriented programming, In classical inheritance, methods from the base class get copied into the derived class. In JavaScript, inheritance is supported using prototype objects. There is two way for apply inheritance property.

Features of inheritance 

  1. inherited the parent property
  2. increase code reusability 
  3. fast accessing
  4. improve security

Using extends keyword

Syntax

class child-class-name extends parent-class-name{
 constructor(){
  // parent constructor calling using super()
  // variable initialization
 }
}
Example
<!DOCTYPE html>
<html>
<body>
<p id='demo'></p>
<script>
class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}
let myCar = new Model('Ford', 'Mustang');
document.getElementById('demo').innerHTML = myCar.show();
</script>
</body>
</html>

Using prototype function

class_name.prototype.prototype_name= function() {

 statement
};
<!DOCTYPE html>
<html>
<body>
 <script>
// prototype Parent class
function Person(firstName, lastName) {
  this.FirstName = firstName ;
  this.LastName = lastName ;
 }
Person.prototype.getFullName = function () {
  return this.FirstName + ' ' + this.LastName;
 }
// Student prototype function
function Student(firstName, lastName, schoolName, grade)
 {
  Person.call(this, firstName, lastName);
  this.SchoolName = schoolName ;
  this.Grade = grade;
 }
//Student.prototype = Person.prototype;
Student.prototype = new Person();
Student.prototype.constructor = Student;
var std = new Student('James','Bond', 'XYZ', 10);
document.writeln(std.getFullName()); // James Bond
 </script>
</body>
</html>



Loading...
Ads