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 {…}
Example:-
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 classclass Profile {// Constructor of profile classconstructor(name, age) {this.name = name;this.age = age;}getName() {// Method to return namereturnthis.name;}getAge() {// Method to return agereturnthis.age;}getClass() {returnthis;}}// Class Student extends class Profileclass Student extends Profile {// Each data of class Profile can be// accessed from student class.constructor(name, age, languages) {// Acquiring of attributes of parent classsuper(name, age);this.lang = [...languages];}// Method to display all attributesgetDetails() {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 }