What is classes & Inheritance in js

๐Ÿ”—What is class ?

JavaScript Classes are templates for JavaScript Objects. class encapsulates data and functions that manipulate data

**syntax**

js
class MyClass {
constructor() { ... }
}

Define a class :- in this example we created a class named "User", with the two properties "name" and "country".

js
class User {
constructor(name, country) {
this.name = name;
this.country = country;
}
}

Using a Class :- When you have a class, you can use the class to create objects:

js
let user1 = new User("Sumit", "India");
console.log(`Hello i am ${user1.name} from ${user1.country}`);

The class Method :- in this example we created a class named "myAge", with properties "year" and age() method.

js
class myAge {
constructor(year) {
this.year = year;
}
age() {
return year - this.year;
}
}
let date = new Date();
let year = date.getFullYear();
let howold = new myAge(2001);
console.log("I'm" + " " + howold.age() + " years old.");
// I'm 20 years old.

๐Ÿ”—What is Class Inheritance ?

Class inheritance is a way for one class to extend another class using extend keyword and super method

Inheritance is useful for code reusability reuse properties and methods of an existing class when you create a new class.

Parents class

js
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return "I have a " + this.carname;
}
}

Extending Model class to parent car class

js
class Model extends Car {
constructor(brand, mod) {
// super method to get access of parents class properties and method
super(brand);
this.model = mod;
}
show() {
return this.present() + ", it is a " + this.model;
}
}
let myCar = new Model("THAR", "AX Opt");
console.log(myCar.show());
Extending Model class to parent car class