JavaScript Class

We talked about objects, which are one of the most interesting parts of JavaScript.

In this chapter we'll go up one level, introducing classes.

What are classes? They are a way to define a common pattern for multiple objects.

Let's take a person object:


let person = { 
  user: "Codingkoleji"
};
            

We can create a class named Person(note the capital P , a convention when using classes), that has a nameproperty:


class Person { 
  user
}
            

Now from this class, we initialize a codingkoleji object like this:


let codingkoleji = new Person();

codingkolejiis called an instance of the Person class.

We can set the value of the userproperty.


codingkoleji.user = "Codingkoleji";

and we can access it using


codingkoleji.user;

like we do for object properties.

Example


class Person { 
  user
}

let codingkoleji = new Person();
codingkoleji.user = "Codingkoleji";
console.log(codingkoleji.user);
  

Classes can hold properties, like user, and methods.

Methods are defined in this way:


class Person {
  hello(){  
    return "Hello, I am Codingkoleji";
  }
};
            

and we can invoke methods on an instance of the class:


class Person {
  hello(){  
    return "Hello, I am Codingkoleji";
  }
};

const codingkoleji = new Person();
codingkoleji.hello();
            

Example


class Person {
  hello(){  
    return "Hello, I am Codingkoleji";
  }
};

const codingkoleji = new Person();
console.log(codingkoleji.hello());
  

There is a special method called constructor()that we can use to initialize the class properties when we create a new object instance.

It works like this:


class Person {
  constructor(user){
    this.user = user
  }
}

hello(){  
  return "Hello, I am " + this.user + ".";
}
            

Note how we use thisto access the object instance.

Now we can instantiate a new object from the class, passing a string, and when we call hello , we'll get a personalized message:


const codingkoleji = new Person("Codingkoleji");

codingkoleji.hello();//'Hello, I am Codingkoleji'
            

When the object is initialized, the constructor method is called, with any parameters passed.

Example


class Person {
  constructor(user){
    this.user = user;
  }
  hello(){  
    return "Hello, I am " + this.user + ".";
  }
}


const codingkoleji = new Person("Codingkoleji");

console.log(codingkoleji.hello()); //'Hello, I am Codingkoleji'
  

Normally methods are defined on the object instance, not on the class.

You can define a method as static to allow it to be executed on the class instead:


class Person {
  static genericHello(){
    return "Hello";
  }
}

Person.genericHello();  //Output: Hello
            

Example


class Person {
  static genericHello(){
    return "Hello";
  }
}

console.log(Person.genericHello()); //Output: Hello