What is an ES6 Class
- A class is like a blue print which can be used to instantiate new class objects which inherit all the properties and methods from the class they are being instantiated from.
- In ES6 version of Javascript, a new class keyword has been introduced, which allows users to create or instantiate new class objects from a standard class definition.
How do we create a class in Javascript?
- To create a class we use the keyword class followed by any name of your choice (It is always a good practice to capitalize the first letter of a class name).
- Then we open and close a pair of curly brackets after the class name. (Like an empty object).
- As an example we will create a class called "Person" like this:
class Person {}
- Thats it. It is a valid class definition.
How do we instantiate a Class?
- As we already know that class is like a blue print. We can use it to create multiple class objects by instantiating (or creating a new instance of the class).
- Instantiating a class simply means creating a new instance of an existing class definition. The new instance of the class will be simply a class object with all the properties and methods directly inherited from class.
- We can instantiate a new class object by using the "new" keyword like the following. Notice how we instantiate it like a function call (with a pair of parenthesis).
class Person {}const me = new Person();
- If needed, we can pass in some arguments while instantiating a new class like the following:
class Person {}const me = new Person('John Doe')console.log(me)
- Even if we pass the data (In this case a string value 'John Doe') through an argument, nothing will happen because there is no way for a class to collect and do something meaningful with this data.
What is a Constructor function?
- In order for a class to collect this data and do something meaningful, we have to use something called as "constructor" function inside a class definition.
- A constructor funtion gets called everytime we instantiate a class. It gets called with all the arguments that we pass in while creating a new instance of the class.
- A constructor function is completely optional, and we are not bound to use it. A class definition still stands valid even if there is no constructor function. However we will not have the access to the data that is passed as an argument if we don't use a constructor function.
- A constructor function is declared in a class definition like the following:
class Person { constructor() { console.log('Test') }}const me = new Person('John Doe')const other = new Person()
- The example above will log 'Test' in browser console 2 times. It is because the constructor function is called every time a new instance of the class is created.
Everytime you instantiate a class, the constructor function gets called.
Because of constructor function, we can collect the data passed in as arguments when we instantiate a Class.
- In order for constructor function to collect the data that we pass as an argument (while creating a new instance of the class), we have to define those arguments. Lets look at the following example:
class Person { constructor(name, age) { this.name = name this.age = age }}const me = new Person('John Doe', 32)
- In the above example we pass 2 arguments inside the constructor function. Now when we create a new instance of Person, we can pass values which can then be collected by the arguments inside constructor function.
Inside a class definition this refers to the instance of the class (Object).
- In the example above, we use the name value and assign it to this.name. Similarly we use age argument, and assign it to this.age.
- This refers to the new instance of class. In above example "this" referes to a new instance of Person class called "me".
- "me" is going to be a new class object with 2 properties (1) name: 'John Doe', and (2) age: 32. Like the following:
Person { name: 'John Doe', age: 32}
- If you dont pass any argument when creating a new instance of Person class, then it will create a new class object with the name and age values "undefined". In order to avoid this, usually a default value is set for the arguments. That means, if a new class is instantiated with no arguments, then it takes and uses the default arguments and not "undefined".
- It used to be a popular practice in the past to set the default values like this:
class Person { constructor(name) { this.name = name || 'Anonymous' }}const me = new Person()
- In the example above, we are checking if the name argument is not provided or its undefined, then set its value to 'Anonymous'.
- Now in the ES6 classes, it can be done like this:
class Person { constructor(name='Anonymous', age=0) { this.name = name, this.age = age }}
- Notice in the constructor function above we are defaulting the name and age argument values to 'Anonymous', and 0 respectively. If a class is instantiated with no arguments then the default values of name and age is going to be 'Anonymous', and 0.
What is a sub-class?
- A sub-class is a class created from an existing parent class.
- A sub-class by default inherits all the properties and methods of its parent class.
- If needed more properties and methods can be added in a sub-class.
- If needed already existing methods (inherited from parent class) can be modified in a sub-class.
A sub class extends (inherits) all the features of its parent class.
How to create a sub-class?
- To create a sub-class, we use the extends keyword with the parent class name.
- Lets say we want to create a class called "Student".
- Following the examples above, we notice the Student class can be extended from Person class.
- So we can create a sub-class called Student from the parent class Person like this:
/* PARENT CLASS */class Person { constructor(name = 'Anonymous', age=0) { this.name = name this.age = age } getGreeting() { return `Yo..Whatsup. I am ${this.name}.` } getDescription() { return `${this.name} is ${this.age} years old.` }}/* CREATING A NEW SUB-CLASS FROM PARENT CLASS */class Student extends Person { }/* INSTANTIATING THE NEW SUB-CLASS */const me = new Student('John Doe', 32)console.log(me)console.log(me.getDescription())const other = new Student()console.log(other)console.log(other.getDescription())
- In this example above we create a sub-class called Student which inherits all the features from its parent class called Person.
- This is the reason why, even if we haven't defined any properties, or methods, or a constructor function in the newly created class Student, we can still use the properties and methods defined in the parent class.
- Notice that we have the a getDescription method defined in the parent class, and I can use it in the sub-class without the need of re-defining it.
How to modify a sub-class?
- In the example above, I can pass a person's name and age as arguments when creating a new instance of the Class definition.
- Lets say for Student class, I want to pass in an extra argument called major when creating a new instance of Student class.
- So I can do something like this:
/* CREATING A NEW SUB-CLASS FROM PARENT CLASS */class Student extends Person { }/* INSTANTIATING THE NEW SUB-CLASS */const me = new Student('John Doe', 32, 'Computer Science')console.log(me)
- In the example above, I am passing in an extra argument called 'Computer Science' which I would like to collect as a new argument in the class called major.
- In order to collect this argument we need to create a constructor function (with all the arguments that I would like to pass) in Student class like this:
/* CREATING A NEW SUB-CLASS FROM PARENT CLASS */class Student extends Person { constructor(name = 'Anonymous', age = 0, major = 'Undecided') { this.major = major }}/* INSTANTIATING THE NEW SUB-CLASS */const me = new Student('John Doe', 32, 'Computer Science')console.log(me)
- Notice that I am passing 3 arguments in the constructor function with their default values.
- name = 'Anonymous'
- age = 0
- major = 'Undecided'
- Now we can use major argument to collect the value of major, and assign it to this.major.
- Inside a class definition this refers to the instance of the class (Object).
- Notice, we are only doing it for major, and we are not doing it for name, and age because the constructor function in the parent class Person already does that.
- Now when we run the code above, you will notice that it will not work.
- In order to understand why the code didn't work, we have to understand what is super function.
What is super ?
- In a sub-class when you create a constructor function, it needs to call the constructor function of its parent class before it can do anything.
- In order to call the constructor function from the parent class we use a function called super().
- We have to pass in the arguments in super function, that we would want to pass to the constructor function of parent class.
- To make the above code work, we have to make some small changes like this:
/* CREATING A NEW SUB-CLASS FROM PARENT CLASS */class Student extends Person { constructor(name = 'Anonymous', age = 0, major = 'Undecided') { super(name, age) this.major = major }}/* INSTANTIATING THE NEW SUB-CLASS */const me = new Student('John Doe', 32, 'Computer Science')console.log(me)const other = new Student()console.log(other)
- Notice in the code above, we just added the super() function with the name and age arguments (which gets passed to the constructor function of parent class Person). Now the code works perfectly as expected.
- Following is the output of the code above.
Student {name: "John Doe", age: 32, major: "Computer Science"}Student {name: "Anonymous", age: 0, major: "Undecided"}
What else can super do?
- With super keyword, we can also access the methods defined in the parent class.
- Lets look at the following scenario and try to understand this concept.
- Lets say in the new sub-class Student we would like to edit the getDescription method that is already defined in the parent class Person.
- We can completely override the parent class method by simply re-defining the new method in the sub-class like this:
class Student extends Person { constructor(name = 'Anonymous', age = 0, major = 'Computer Science') { super(name, age) this.major = major } getDescription() { return 'This is the new edited description' }}const me = new Student('John Doe', 32, 'Computer Science')console.log(me.getDescription())
- You will notice that the new getDescription method defined in the sub-class overrides the parent class method.
- Now lets add a new logic into the mix. Instead of completely overriding the parent method, we would conditionally add an extra statement to the parent method's return statement.
- Currently the getDescription defined in parent class Person returns the following:
${this.name} is ${this.age} years old.. - Now in the Student class we would like to add an extra line of statement (after the existing one) if the student has a major subject passed as an argument.
- So we would like to add an extra line -
${this.name} has a major in ${this.major}if the student has a major. - To get the return statement from parent class's getDescription method, we will again use the super keyword.
- Let's see how we can do that:
class Student extends Person { constructor(name = 'Anonymous', age = 0, major = 'Computer Science') { super(name, age) this.major = major } getDescription() { let parentDesc = super.getDescription() if (this.major !== 'Undecided') { parentDesc += ` ${this.name} has major in ${this.major}.` } return parentDesc }}const me = new Student('John Doe', 32, 'Computer Science')console.log(me.getDescription())
By leveraging ES6 classes, JavaScript developers can write cleaner, more maintainable code. Whether you're creating reusable templates or building scalable applications, understanding classes is fundamental to mastering modern JavaScript.
