Classes and sub classes in javascript
Class in javascript
Classes are the function which is used to define expression and declarations. Basically the Java script is a classless language, it supports the object.In the javascript class work in the same way like other language that's why classes are called syntactic sugar .
class student{
constructor(motherName,fatherName){
this.motherName = motherName;
this.fatherName = fatherName;
}
};
const riva = new student('Mrsriva','Mrsumit');
console.log(riva);
Adding Methods
class Student{
constructor(motherName,fatherName){
this.motherName = motherName;
this.fatherName = fatherName;
}
intro(){
return `Hello my name is Deep my parents name is ${this.motherName} ${this.fatherName}`;
}
}
const name= new Student('Mrs Riva','Mr Sumit');
console.log(name.intro());
Any method which we add inside the class that method are added in the prototype
instead of this console.log(name.intro()); use console.log(name); we get intro() method in prototype
Calculate Numbers
class Student{
constructor(Name,dob){
this.Name = Name;
this.birthday = new Date(dob);
}
studentAge() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1980);
}
}
const Name = new Student('Riva', '11-4-1993');
console.log(Name.studentAge());
like above here also method are added in prototype
Subclass in javascript
As we know that class are the blueprint. Just like any other language like Java or PHP, Javascript follow the inheritance property for making subclasses.It creates a constructor and and each constructor inherit the property of others including their own property.
class student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
intro() {
return `Hello i am ${this.firstName} ${this.lastName}`;
}
}
class Studentdetails extends student {
constructor(firstName, lastName, phone, address) {
super(firstName, lastName);
this.phone = phone;
this.address = address;
}
}
const name = new Studentdetails('Deep', 'Singh', '555-555-5555', 'Pk street sector 45 Noida');
console.log(name);
we can use anything from the student in studentdetails because we extend it.
Creating Static method
class student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
intro() {
return `Hello i am ${this.firstName} ${this.lastName}`;
}
}
class Studentdetails extends student {
constructor(firstName, lastName, phone, address) {
super(firstName, lastName);
this.phone = phone;
this.address = address;
}
static Annualfees() {
return 10000;
}
}
const name = new Studentdetails('Deep', 'Singh', '555-555-5555', 'Pk street sector 45 Noida');
console.log(name);
console.log(Studentdetails.Annualfees());