DEV Community

Asif Zubayer Palak
Asif Zubayer Palak

Posted on • Edited on

2

JS Classes: Classes and Constructors

What are classes?

Classes are a template for creating objects. Use the keyword class to create a class.
Always add a method named constructor()

Creating a new class

class Car{
 constructor(brand, model, color){
  this.brand = brand;
  this.model = model;
  this.color = color;
  this.sold = false;
 }
 carSold(){
  this.sold = true;
 }
}
Enter fullscreen mode Exit fullscreen mode

We create a class with the class keyword and then create the constructor function.

The constructor function immediately gets invoked when we create an object using this class.

You might notice that there is a function

carSold(){
  this.sold = true;
 }
Enter fullscreen mode Exit fullscreen mode

Which is actually in the ES6 syntax. Normally, you'd see this function written like:

this.carSold = function(){
 this.sold = true;
}
Enter fullscreen mode Exit fullscreen mode

Creating an object with the class

Now as you're done creating the class, time to create an object with it.
To do this you need to type in:
let <object_name> = new <class_name>(<parameters>)

For example, for the class stated above:

let car1 = new Car('Toyota','Sienna','Blue')'
Enter fullscreen mode Exit fullscreen mode

This would create an object car1 of Brand: Toyota, Model: Sienna and Color: Blue.

Here, the parameters inside the round brackets are passed to the constructor and thus sets the Brand to Toyota, Model to Sienna and Color to Blue.

Initially its sold status is set to false.
This is changed by calling the carSold() function.
So if you call car1.carSold() - the value of car1.sold will be true

To learn about the Extend and Super keyword, check out JS Classes: Extend and Super Keyword

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️