Inheritance in JS

Inheritance in JS

Inheritance is the property by which one class can get the property of another class. This feature is also known as re-usability. One class inherit the another class using keyword extends.

Example 1 – using Function

<script>

class First {

    firstnumber(firstNumber)

            {

                        this.f=firstNumber;

                        console.log(“First Number is ” + this.f);

            }

}

class Second extends First {

   secondnumber(secondNumber)

            {

                        this.s=secondNumber;

                        console.log(“Second Number is ” + this.s);

            }

            add(){

            console.log(this.f +this.s);

            }

}

let sum=new Second();

sum.firstnumber(4);

sum.secondnumber(5);

sum.add();

</script>

Example 2 – using constructor

Concept is same but we use supar class if inherit from base class constructor

<script>

class First {

            constructor(firstNumber)

            {

                        this.f=firstNumber;

                        console.log(“First Number is ” + this.f);

            }

}

class Second extends First {

            constructor(firstNumber,secondNumber)

            {

                        super(firstNumber);

                        this.s=secondNumber;

                        console.log(“Second Number is ” + this.s);   

            }

            add(){

            console.log(this.f +this.s);

            }

}

let sum=new Second(4,5);

sum.add();

</script>

2 thoughts on “Inheritance in JS

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*