Enough talking, let’s explore how to start writing our classes, so you can see why they are so powerful!
class
KeywordThe first thing we need is a new keyword! To write a class, we are going to use the keyword class
.
The class name always follows this keyword.
An open curly brace follows the name, and the class ends with a closing curly brace. The curly braces contain properties/attributes and methods.
Before we can go further, let’s first talk about class naming conventions. For all except one rule, you should follow the same naming conventions that you do for variable names.
The one exception is that you should start class names with a capital letter.
In practice, defining a class will have the following structure.
class MyFavoriteClass {
// class methods/functions
}
When defining a class, functions are the things that do stuff in the class.
Methods is written within the function block - between the curly braces - of a class definition.
Writing methods within classes is practically identical to defining standalone functions.
To write a method, you simply need to write its name, following function naming conventions (i.e. lower case letter to start the method name).
Parentheses contain any input parameters for the specific method.
Finally, you add a function block ({}
). You will put all of the stuff for the method to do, within this function block.
To write multiple methods, separate each function with a new line. (This is more for the style than anything error specific). Then repeat the above steps.
// a class definition
class MyFavoriteClass {
// method 1
sayHello( name1, name2 ) {
// method function block
// Do stuff here
console.log(name1 + " says hello to " + name2);
}
// another method
callMeCharlie() {
// method function block
console.log("Well call me Charlie");
}
}
Not bad, right? Let’s take a look at the constructor.