DEV Community

SCDan0624
SCDan0624

Posted on

2 1

Intro to Classes

Intro
New to ES6 is a type of function called classes. Each class has the ability to generate new versions of itself called instances. Each class instance can contain unique data. Let's take a closer look at classes and how to write them.

Syntax
Writing a class is similar to writing a normal function, expect we use the keyword class in place of the keyword function:

class Car {}
Enter fullscreen mode Exit fullscreen mode

To create an instance of a class we use the constructor method:

class Car{
  constructor(brand,year){
    this.brand = brand;
    this.year = year;
  }
}
Enter fullscreen mode Exit fullscreen mode

Using the new syntax we can create an instance of the Car class:

class Car{
  constructor(brand,year){
    this.brand = brand;
    this.year = year;
  }
}

let myCar = new Car("Ford", 1997) 
// Car { brand: 'Ford', year: 1997 }
Enter fullscreen mode Exit fullscreen mode

If you need to access instance properties you can use dot notation or brackets:

class Car{
  constructor(brand,year){
    this.brand = brand;
    this.year = year;
  }
}

let myCar = new Car("Ford", 1997) 
// Car { brand: 'Ford', year: 1997 }

myCar.brand 
// 'Ford'
myCar.year 
// 1997

myCar["year"] 
// 1997
Enter fullscreen mode Exit fullscreen mode

You can even access properties outside the instance in a class method:

class Car{
  constructor(brand,year){
    this.brand = brand;
    this.year = year;
  }

  myBrand(){
    return `My car personal car is a ${this.brand}`
  }
}

let myCar = new Car("Honda",2009)

myCar.myBrand() 
//'My car personal car is a Honda'

Enter fullscreen mode Exit fullscreen mode

Hoisting
Unlike regular functions classes are not hoisted. You must declare a class before using it.

//You cannot use the class yet.
// let mycar = new Car("Ford",2020)
//This would raise an error.

class Car {
  constructor(brand,year) {
    this.carname = brand;
  }
}

//Now you can use the class:
let mycar = new Car("Ford",2020)
Enter fullscreen mode Exit fullscreen mode

Conclusion
Now that you have the basics of classes and instances down. Practice writing some on your own. Just remember they will not be hoisted.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay