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 {}
To create an instance of a class we use the constructor method:
class Car{ constructor(brand,year){ this.brand = brand; this.year = year; } }
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 }
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
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'
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)
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.
Top comments (0)