DEV Community

Cover image for How to build an object with 'Class Constructors' in Javascript
Karem
Karem

Posted on • Originally published at karemortiz.nl

How to build an object with 'Class Constructors' in Javascript

Whilst I was creating a weather app with Javascript, I was confused about what a class constructor does.

Therefore, I decided to research about it and help others to understand how to work with them.

A class constructor is nothing more than a way to create an object in ES6 so is a new way but incredibly useful to create and build applications.

For example, you can create a 'user search application' using an API, a Weather app or any application that requires the use of APIs.

  1. You need to create a class with a name: follow the UpperCaseCamel rule, which means that every word starts with a capital letter.

class Cat {}

  1. Create the constructor: the constructor is simply a way to create our object and the syntax is:

class Cat {
constructor() {

}
}

  1. Create the constructor

The keyword this is very important because it points out 'which' object we want to create.
Don't forget to give it an intuitive name everyone will be able to recognize (developer team, clients)

class Cat {
constructor() {
this.treat = 'catnip'
}
}

  1. Call or invoke the object

class Cat {
constructor() {
this.treat = 'catnip'
}
}

const catnip = new Cat('catnip')
console.log(catnip.treat) //'catnip'

I created an easy step by step infographic that you can download here:
https://karemortiz.nl/class-constructor-javascript/

Top comments (1)

Collapse
 
marcusatlocalhost profile image
Marcus

Thanks for your contribution. Would you mind, wrapping the code blocks with backticks so they get syntaxhighlighting? That would be great. Thank you.

github.com/adam-p/markdown-here/wi...