JavaScript Constructor Functions and Classes

Published on
5 mins read
––– views

What are Classes?

JavaScript classes allow creating templates for objects, similar to blueprints. This helps in creating reusable and maintainable code.

For example, in an online t-shirt store, instead of writing separate code for each t-shirt, a class "Tshirt" with properties such as color, size, and print can be created. Each time a new t-shirt is needed, a new instance of the class can be created with specific values for its properties. This saves time and makes the code more organized.

Here is an example code, do not worry we will break it down.

class Tshirt {
  color
  size
  print

  // classes can have "functions" inside, which are called methods.
  calculatePrice() {
    // some code
  }
}

const tshirt1 = new Tshirt()
tshirt1.color = 'red'
tshirt1.size = 'L'
tshirt1.print = 'graphic'

const tshirt2 = new Tshirt()
tshirt2.color = 'blue'
tshirt2.size = 'M'
tshirt2.print = 'plain'

console.log(tshirt1) // Tshirt {color: 'red', size: 'L', print: 'graphic'}
console.log(tshirt2) // Tshirt {color: 'blue', size: 'M', print: 'plain'}

JavaScript classes are used to create templates for objects that can be reused in your code. When naming a class, the first letter should always be a capital letter, such as Tshirt. To create a new instance of the class, use the new keyword, like so: const tshirt1 = new Tshirt();. This lets JavaScript know that the tshirt1 variable is related to the Tshirt class.

Once an instance of the class has been created, you can access and assign values to its properties using dot notation. For example, tshirt1.color = 'red'. However, to be able to access and assign values to the properties, they must first be declared inside the class. The properties, such as color, size, and print, serve as the unique characteristics of each instance of the class.

Code above works, but we can make it even better.

What are Constructor Functions?

Think of it like a cookie factory that makes different types of cookies. Each type of cookie has its own properties, like the type of chips or raisins it contains. Instead of writing new code for each type of cookie, you can use a constructor function. The constructor function would define what all cookies should have, like the properties "type" and "flavor".

Then, whenever you want to create a new type of cookie, like chocolate chip or raisin, you just create a new instance of the constructor function with the specific values for its properties. This saves you time and keeps your code neat and organized.

Constructor functions are a great tool for creating similar objects with different properties in JavaScript and for making your code more maintainable and efficient!

Here is an example code

class Cookie {
  // constructor is a build-in function.
  constructor(type, flavor, shape = 'round', frosting = false) {
    this.type = type
    this.flavor = flavor
    this.shape = shape
    this.frosting = frosting
  }
}
// this cookie assigns value for each property
const sugarCookie = new Cookie('Sugar', 'Sweet', 'star', true)
//
// to use default values, use `undefined`, like on this example
const oatmealCookie = new Cookie('oatmeal', 'Cinnamon', undefined, true)
// oatmealCookie will have  oatmeal, cinnamon, round and true
//
// if rest of the properties have default values, you can skip them.
const raisinCookie = new Cookie('Raisin', 'Fruit')
// raisinCookie will have raisin, fruit, round and false

Here, we declared a constructor function inside our Cookie class. Cookies can share some properties and have unique properties, like the flavor, but most cookies are round. Needed properties will be passed like parameters in functions.

class Cookie {
  // constructor is a build-in function.
  constructor(type, flavor, shape = 'round', frosting = false) {
    this.type = type
    this.flavor = flavor
    this.shape = shape
    this.frosting = frosting
  }
}

If a property is common for most products, we can give them a default value. constructor(shape = 'round') {} . Some properties will be unique for that type of cookie, like the flavor. Raisin cookie won't taste like chocolate chip. So, assigning default values to flavor and type may not make much sense.

constructor(type, flavor, shape = 'round', frosting = false){ /* code */}

to use default values, the keyword undefined is needed. const newCookie = new Cookie('Chocolate Chip', 'Sweet', undefined, true)

undefined will be equal to round because that's the default value. Cookie { type: 'Chocolate Chip', flavor: 'Sweet', shape: 'round', frosting: true }


So, what is this.type and this.flavor means? This keyword can be really tricky, and do not worry if you don't get it on the first try. understanding this takes time.

class Cookie {
  constructor(type, flavor, shape = 'round', frosting = false) {
    this.type = type
    this.flavor = flavor
    this.shape = shape
    this.frosting = frosting
  }
}

In a class, the this keyword refers to the instance of the class. For example, in the class Cookie, this.type and this.flavor refer to the type and flavor properties of a specific cookie (like oatmeal or chocolate chip) instance created from that class. The value of this changes depending on the instance, so each instance can have its own unique values for its properties.

each new cookie we create is an instance