OOP in JS: Classes

Classes are a way to define a common pattern for multiple objects definitions.

In other words, you define a class and then all objects that you create from that class have the same properties and methods of the class.

It’s like a template.

We can create a class named Person (note the capital P, a convention when using classes), that has a name property:

class Person {

You can set a default value using this syntax:

class Person {
  name = 'Flavio'

Note: remember, don’t use a : colon for class properties, but use =. It’s a bit confusing with object properties.

Now from this class, we initialize a flavio object like this:

const flavio = new Person()

flavio is called an instance of the Person class, and inherits all the properties (and methods, too, as we’ll see) of the Person class.

We can now access the name property on flavio using the dot syntax we use for objects:

flavio.name = 'Flavio'

Lessons in this unit:

0: Introduction
1: ▶︎ Classes
2: Class methods
3: Private class properties
4: Constructors
5: Inheritance
6: Prototypes
Want to learn more? Check out our courses