The extends keyword can be used to extend the objects as well as classes in JavaScript. It is usually used to create a class which is child of another class.
Syntax:
class childclass extends parentclass {...}
class parentclass extends in-built object {...}
Below example depicts how a child class uses properties of parent class using the keyword extends and by creating objects of the child class. In example 1, we see that class Profile has two attributes name and age. Now we will see that class Student acquires both attributes of class Profile using the keyword extends with an added attribute languages and then all attributes are displayed.
Example 1: In this example, we use the extends keyword.
- Program:
<script>   Â// Declaring class   Âclass Profile {        Â       Â// Constructor of profile class       Âconstructor(name, age) {           Âthis.name = name;           Âthis.age = age;       Â}       ÂgetName() {            Â           Â// Method to return name           Âreturnthis.name;       Â}       ÂgetAge() {            Â           Â// Method to return age           Âreturnthis.age;       Â}       ÂgetClass() {           Âreturnthis;       Â}   Â}ÂÂ// Class Student extends class ProfileÂclass Student extends Profile {    Â   Â// Each data of class Profile can be   Â// accessed from student class.   Âconstructor(name, age, languages) {        Â       Â// Acquiring of attributes of parent class       Âsuper(name, age);       Âthis.lang = [...languages];   Â}   Â// Method to display all attributes   ÂgetDetails() {       Âconsole.log("Name : "+this.name);       Âconsole.log("Age : "+this.age);       Âconsole.log("Languages : "+this.lang);   Â}}ÂÂ// Creating object of child class with passing of valuesvarstudent1 =newStudent("Ankit Dholakia", 24,           Â['Java','Python','PHP','JavaScript']);student1.getDetails();Â</script> - Output:
Name : Ankit Dholakia Age : 24 Languages : Java,Python,PHP,JavaScript
Example 2: In this example, we will see how spread syntax can be used to extend two objects into a third object and display the containing attributes of both objects.
- Program:
<script>// Creating first objectvarobj1 = {    Âname:'Ankit',    Âage: 20};ÂÂ// Creating second objectvarobj2 = {   Âmarks: 50};ÂÂ// Using spread syntax to extend// both objects into onevarobject = {   Â...obj1,   Â...obj2};console.log(object);Â</script> - Output:
{ name: 'Ankit', age: 20, marks: 50 }
