OOP in JS: Constructors

You can create an object from the class passing arguments that are then stored inside the object.

We do so using a constructor, a special method of the class.

Here’s an example:

class Person {
  constructor(name) {
    this.name = name
  }
}

When the object is initialized, the constructor method is called, with any parameters passed.

const flavio = new Person('Flavio')

Now we can add methods that use the name property:

class Person {
  constructor(name) {
    this.name = name
  }

  hello() {
    return 'Hello, I am ' + this.name + '.'
  }
}

Notice we used this to reference the class. This is another place where you are going to use this special JavaScript keyword, other than in object methods.

Lessons this unit:

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