()
Understanding JavaScript’s super()
The super()
keyword is an important part of the JavaScript language and is used in object-oriented programming. It is used to refer to a parent class or object, and can be used to call methods or access properties of the parent.
What is super()?
The super()
keyword is used to refer to a parent class or object, and can be used to call methods or access properties of the parent. It is used in object-oriented programming to refer to the parent of the current object.
It is important to note that super()
must be used within a class definition. It cannot be used outside of the class.
How to Use super()
In order to use the super()
keyword, you must first create a class that has a parent class. For example, we could create a Person
class and a Student
class that inherits from Person
:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
class Person {
constructor(name){
this.name = name;
}
sayName(){
console.log(this.name);
}
}
class Student extends Person {
constructor(name, grade){
super(name);
this.grade = grade;
}
sayGrade(){
console.log(this.grade);
}
}
[/dm_code_snippet]
In this example, the Student
class is a child class of the Person
class. The super()
keyword is used in the Student
class constructor to call the parent Person
class constructor and pass in the name
argument. This allows us to access the name
property in the Student
class.
We can also use the super()
keyword to access methods in the parent class. For example, we could add a sayName()
method to the Student
class that calls the sayName()
method of the parent Person
class:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
class Student extends Person {
constructor(name, grade){
super(name);
this.grade = grade;
}
sayName(){
super.sayName();
}
sayGrade(){
console.log(this.grade);
}
}
[/dm_code_snippet]
In this example, the sayName()
method of the Student
class calls the sayName()
method of the Person
class using the super()
keyword.
Conclusion
The super()
keyword is an important part of the JavaScript language and is used in object-oriented programming. It is used to refer to a parent class or object, and can be used to call methods or access properties of the parent. It is important to note that super()
must be used within a class definition, and cannot be used outside of the class.