What is inheritance in JavaScript explain the all inheritance?

0 votes
29 views
Ravi Vishwakarma asked 13 days ago in Web Application by Ravi Vishwakarma

What is inheritance in JavaScript explain the all inheritance?    

1 Answer

0 votes
Ethan Karla answered 10 days ago by Ethan Karla
Inheritance is an important concept in object oriented programming. In the classical inheritance, methods from base class get copied into derived class. In JavaScript, inheritance is supported by using prototype object. There are two way for apply inheritance property.
1. Using extends keyword
2. Using prototype function
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>Use the 'extends' keyword to inherit all methods from another class.</p>
<p>Use the 'super' method to call the parent's constructor function.</p>
<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
  Let's see how we can achieve inheritance functionality in JavaScript using prototype object. Let's start with the Person class which includes FirstName & LastName property as shown below.
<!DOCTYPE html>

<html>
<body>
 <script>
// prototype Parent class
function Person(firstName, lastName) {
  this.FirstName = firstName || 'unknown';
  this.LastName = lastName || 'unknown';
 }
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 || 'unknown';
  this.Grade = grade || 0;
 }
//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
document.writeln(' <br />'+ std instanceof Student); // true
document.writeln(' <br />'+ std instanceof Person); // true
 </script>
</body>
</html>