Submodule 13.2: JavaScript classes

Methods inside JavaScript classes

Since JavaScript classes act as the template to create new objects, they can also contain methods.

An example of a class with a method would be:

class Dishes {
constructor(category, price) {
    this.category = category;
    this.price = price;
  }
output (){
console.log("This belongs to" + " " +this.category + " " + "and costs" + " " + this.price);
}
}

From the above example, we see that the methods inside classes do not start with function. We define methods just by giving them a name followed by (). 

In order to call the method in an object that we have created, the syntax is:

objectName.methodName();

For example, for our previous example:

 let dish1;
dish1 = new Dishes  ("sweets", 5);

We can call the output method by writing:

 dish1.output();

What do you think, will be the console output of the above code?

Answer:

The output will be: "This belongs to sweets and costs 5"
Examples

See more about JavaScript classes