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 {
  name
}

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'
console.log(flavio.name)

Lessons in this unit:

0: Introduction
1: ▶︎ Classes
2: Class methods
3: Private class properties
4: Constructors
5: Inheritance
6: Prototypes
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!