Enough talking, let’s explore how to start writing our own 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
.
This keyword is always followed by the class namespace.
The namespace is followed by a function block, which contains the methods defining the class.
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 ClassName {
// class methods
}
When defining a class, methods are the “how-to” of the class. You can think of methods as a class specific function.
Methods are written within the function block 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).
This is then followed by a set of parentheses containing 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, simply separate each method with a new line. (This is more for style than anything error specific). Then repeat the above steps.
// a class definition
class ClassName {
// method 1
method1( inputParameter1, inputParameter2 ) {
// method function block
// Do stuff here
console.log(inputParemeter1);
}
// another method
anotherMethod() {
// method function block
// Do stuff here
}
}