Classes in ES6
A class is a blueprint for creating objects.
Classes were introduced in ES6 and make object-oriented programming easier to write and understand.
1. Creating a Class
Use the class keyword to create a class.
Here, Student is the name of the class.
2. Constructor
A constructor is a special method that runs automatically when an object is created.
The constructor() is used to initialize the object's properties.
3. Methods
A method is a function defined inside a class.
Here, greet() is a method.
4. Creating Objects
Use the new keyword to create an object from a class.
Now we can use the object's method:
5. extends
extends is used to create a class that inherits from another class.
Here, Student inherits from Person.
6. Inheritance
Inheritance means one class can use the properties and methods of another class.
Now Student can use the name property and greet() method.
Output:
7. super
super() is used to call the constructor of the parent class.
Here:
calls the Person constructor.
Then:
adds a property specific to Student.
Complete Example
Output: