Variables can be used to hold information about the state your code is in, e.g. how many times someone has clicked on a button:
However, you may end up being in a situation where you'll have to keep track of the click state of multiple buttons, or even a dynamic number of buttons:
class (not the same as a class in CSS). Classes are templates which are used to create objects containing methods and properties of the class. For example here the class
Counter ties together the state,
timesClicked, and the functions that reference it like
We can create instances of a class using the
new operator, followed by the class name. When a class instance is created, its
constructor function is called automatically. We can pass the constructor arguments to use during initialisation.
For example, here is a
CounterFromN class that starts counting from a number that's passed in:
As shown above, a class' functions can be called by referring to the name of the object's function followed by brackets. If the function expects any arguments then these can be passed into it inside the brackets as per normal. Functions defined within classes are also be known as methods.
Variables specific to a particular instance of a class are defined and referenced using the
this keyword (e.g.
this.timesClicked) within that instance.
this refers to the object which is created by the class when it instantiated.
Try these exercises in your breakout groups.
getTotal methods of the
RunningTotal class below.
constructor method of the
StopWatch class below.
store and the
lookup methods of the
AddressBook class below.
Notice that when you come to using a class instance, you are only interacting with it through its methods, e.g.
AddressBook. Similar to functions, classes provide a way of creating abstractions over lower-level implementations, which can help us better organise and maintain our code.