OOP in JS: Class methods

Just like you can add methods to objects, you can add methods to classes.

Methods are defined in this way:

class Person {
  hello() {
    return 'Hello, I am Flavio'
  }
}

A class method is like a function, but without the function keyword.

We can invoke methods on an instance of the class:

class Person {
  hello() {
    return 'Hello, I am Flavio'
  }
}

const flavio = new Person()

flavio.hello()
//Hello, I am Flavio

If you are wondering what is the difference with methods defined on object literals:

const car = {
  start: function() {
    console.log("Car engine started")
  },
}

There’s no difference, apart from the fact that all objects instantiated from the class will inherit the method, so they don’t need to define it themselves.

Lessons in this unit:

0: Introduction
1: Classes
2: ▶︎ Class methods
3: Private class properties
4: Constructors
5: Inheritance
6: Prototypes