Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is super() function in JavaScript?
The super() function in JavaScript is used to call the constructor of the parent class and access methods from the parent class within a child class. It's essential for proper inheritance in ES6 classes.
Syntax
super() // Call parent constructor super.method() // Call parent method
Using super() in Constructor
When extending a class, you must call super() before using this in the child constructor:
<!DOCTYPE html>
<html>
<body>
<script>
class Department {
constructor(name) {
this.name = name;
console.log(`Department created: ${this.name}`);
}
}
class Employee extends Department {
constructor(name, id) {
super(name); // Must call super() first
this.id = id;
console.log(`Employee created with ID: ${this.id}`);
}
}
const emp = new Employee("Engineering", 101);
</script>
</body>
</html>
Department created: Engineering Employee created with ID: 101
Using super() for Method Access
You can also use super to call parent class methods:
<!DOCTYPE html>
<html>
<body>
<script>
class Department {
constructor() {}
static msg() {
return 'Hello';
}
getInfo() {
return 'Department Info';
}
}
class Employee extends Department {
constructor() {
super();
}
static displayMsg() {
return super.msg() + ' World!';
}
getInfo() {
return super.getInfo() + ' - Employee Details';
}
}
console.log(Employee.displayMsg());
const emp = new Employee();
console.log(emp.getInfo());
</script>
</body>
</html>
Hello World! Department Info - Employee Details
Key Rules
-
super()must be called before usingthisin a child constructor -
super.method()calls the parent's version of a method - In static methods, use
super.staticMethod()to call parent static methods - Cannot use
superin regular functions, only in class methods
Conclusion
The super() function enables proper inheritance by calling parent constructors and accessing parent methods. Always call super() before using this in child class constructors.
Advertisements
