Classes

Lesson

Classes

What is Classes in JavaScript?

A class is a type of function. It allows creating multiple objects by using keyword class instead of ‘function’. From the previous course, we create two-person with the same properties. Instead of creating new objects, again and again, we could use Classes! So will be a class that describes a person would have name age etc properties assigned by using constructor().

Constructor

The constructor method is creating and initializing an object created with a class. There only gonna have one constructor shows in the class.

let person = class{       //or using ' class person {..}'
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
}

Let’s create an object based on the Class!

Prototype!

Before we move on, we have to know what is the Prototype. JS is a prototype-based language. that means that when you create an object, that object auto gets a prototype and if there is a property or a method that’s not in the object, JS will go to prototype looking to see that exists.

Methods

The method created in the classes is been added to the prototype. The constructor function is running when we call a new person. sayHi is added to the prototype of this type of function.

Static Method

What is Static Method?

All of the properties and method we create above they belong to that particular instance. When we want to create a method that doesn’t belong to instance, but belongs to the entire class, we can do that by using the static method! static keyword points out that it’s not an instance method but it belongs to the class person here.

We can create our first static method simply like this:

let person = class{
  static Hello(){
    return "Hello"
  }
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
}

What to do if we want to use the person object inside of the static method? We can send an object as a parameter like this:

Extends Method

What is Extends method?

Extend method is kind of grouping the properties and methods from one class into another class by using extend keyword.

```jsx
let person = class{
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
}

class School extends person {
  constructor(name,age,school) {
    super(name, age);  
    this.school = school;
  }
}
amy = new School("Amy", 12, "CSNS");
alert(amy);

when calling super in any method, it means it calls the method from the class it extends from.

The example here means we call the method from the ‘person’ class. Or we can say inherit the method from the ‘person’ class.

Try it out

Try out the code and see what we got!

@

Not recently active