Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 instance. This is another place where you will use this special JavaScript keyword, in addition to object methods.
Lessons in this unit:
| 0: | Introduction |
| 1: | Classes |
| 2: | Class methods |
| 3: | Private class properties |
| 4: | ▶︎ Constructors |
| 5: | Inheritance |
| 6: | Prototypes |