Assigning class properties in Javascript

Yonatan Kra
InstructorYonatan Kra

Social Share Links

Tweet

Class properties can help you simplify your classes code. In this lesson we will see how to use class properties in javascript classes.

Yonatan Kra: [00:01] I'll create a class Recipe. It will get a name and store it in a property. Now I'll create a new class Pasta that extends Recipe. Inside I'll add a constructor that defines name and tasty properties.

[00:16] I [inaudible] in the browser and go to the console and instantiate a new Pasta. This results in an error because an extension class must call the super method in its constructor.

[00:30] Going back to the code I'll replace the name assignment with the super method and pass the name. Back in the console, I'll refresh and instantiate a new Pasta. The Pasta was instantiated correctly.

[00:44] Looking at our code, it starts to look cumbersome. If I add more properties to Pasta, the constructor will get loaded. We can solve this by defining class properties. Above the constructor I'll define the properties tasty and type. We can now delete the whole constructor.

[01:05] Heading back to the console, we instantiate a new Pasta and see that is working, with the simplified code.