Home

Javascript Classes

Simple Class

(Using Constructor and Instances)

Class names should always be capitalized then follow camelcase format (capitalize start of each word), eg Dog, DogClass, myDogClass, etc.

this. is used to tell the system that what follows (the property name) is part of the class itself.


class Dog {
   constructor(name) { // the constructor tells it to expect a parameter and holds the list of Properties
      this._name = name;
      this._behavior = 0;
   }

Then goes on to create what methods are needed in this class    get name() {
      return this._name;
   }

   get behavior() {
      return this._behavior;
   }

   incrementBehavior() {
      this._behavior ++;
   }
}

const halley = new Dog('Halley');
console.log(halley.name); // Print name value to console - no () used on getters
console.log(halley.behavior); // Print behavior value to console - no () used on getters
halley.incrementBehavior(); // call method to add one to behavior - not a getter so () needed
console.log(halley.name); // Print name value to console - no () used on getters
console.log(halley.behavior); // Print behavior value to console - no () used on getters

The result of running the above code will be printing some output to the console.log :-

Halley
0
Halley
1



Classes

When creating a class the class name should be capitalized and there should always be a constructor.
The constructor builds a collection of properties used in the class.
After the constructor, within the class, you create the methods you require.

Eg...
class Car { //class
    constructor(make, model, engine, ...) { //constructor

    //Properties below...
      this._make = make;
      this._model = model;
      etc...


   } //end of constructor

    //Methods below...
   get make() {
      return this._make;
   }
   get model() {
      return this._model;
   }
   etc...


}//end of class



Constructor

The constructor tells a Class what parameters to expect.
constructor() { } (no parameters)
constructor(p1) { } (1 parameter)
constructor(p1, p2) { } (2 parameters)
...etc.


Although you may see similarities between class and object syntax, there is one important method that sets them apart.
It’s called the constructor method.
JavaScript calls the constructor() method every time it creates a new instance of a class.

The example (in the left pane) expects one parameter - a name.

Top

Properties(s)

Creating properties for the class is all part of the constructor section.
Although when you want to access them (read in their values/update their values) then this is done by using the Getter/Setter methods.

NOTE...
Property names should be prefixed with an underscore (_) which indicate these properties should not be accessed directly.



Methods

The methods you need are held within the class but outside of the constructor section (it may be easier to think of the constructor as a method itself, which has to be the first method).
...Getter's and Setter's are also methods in their own right.

NOTE...
Methods/Functions inside classes do not use function at the start, eg...
myFunction(param1, param2) {...}
and not...
function myFunction(param1, param2) {...}

An example method could be :-

   incrementBehavior() {
      this._behavior ++;
   }
}

Then you would use a GETTER (get) to read in the value of this._behavior eg...
get behavior() {
   return this._behavior;
}


And when you want to use the getter in your code you would say, eg...
const tilly = new Dog("Tilly"); //Create instance of the Dog class//
tilly.incrementBehavior(); //call incrementBehavior method//
alert(tilly.behavior); //call Behavior 'get' method...note you DO NOT use opening/closing brackets on a getter//


Getters(s)

Getters are methods. They are in the format :-

get make() {
   return this._make;
}


and/or you could have

get vehicle() {
   return this._make + " - " + this._model;
}


this is called by
classname.vehicle;
Note... you do NOT include open/close round brackets when calling a getter.



Setters

Setters are methods. They are in the format :-

set make(value) {
   this._make = value;
}


this is called by
classname.make = "Ford";
Note... you do NOT include open/close round brackets when calling a setter.

Top

Static Methods

Static methods can ONLY be accessed via the class they are in (and NOT via any instances of that class you create), for insance...
If you add a static method to a Superclass then it is NOT available through one of the Subclasses.

Eg...

class Animal {
   constructor(name) {
      this._name = name;
      this._behavior = 0;
   }

    static generateName() {
      const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara'];
      const randomNumber = Math.floor(Math.random()*5);
      return names[randomNumber];
   }


}


So when you run...
console.log(Animal.generateName()); // it returns a name.

but if you have a subclass of the Animal class (called Dog) then
console.log(Dog.generateName()); // will return a TypeError

NOTE...
If you create a static method in a subclass (eg in Dog) then you create an instance of the Dog class...
const tilly = new Dog(param1, param2, ...);
then you can only refer to that static method via the Dog class and NOT via the tilly instance of it.


Instance(s)

Creating instances of the class is done by creating a (NEW) variable and linking it to the class.
const myClass = new ClassName(param1, param2, etc);
EG
constructor(p1) { } (1 parameter)
constructor(p1, p2) { } (2 parameters)
...etc

eg...
const halley = new Dog('Halley');

An instance is an object that contains all the property names and methods of a class.

Using our class scenario (see left pane)...
We use the new keyword to create an instance of our Dog class.
Let’s consider the line of code step-by-step.

We create a new variable named halley that will store an instance of our Dog class.
We use the new keyword to generate a new instance of the Dog class.
The new keyword calls the constructor(), runs the code inside of it, and then returns the new instance.
We pass the 'Halley' string to the Dog constructor, which sets the name property to 'Halley'.
Finally, we log the value saved to the name key in our halley object, which logs 'Halley' to the console.


Top

Inheritance

Classes can inherit properties from a Superclass (or Parent Class) if they need the same properties/methods.
This way you do not have to repeat a lot of code in multiple classes.

For instance
You could have a superclass Animal class that holds properties like name, howManyLegs, Nocturnal.

And then you could have Subclasses (or Child Classes) like Dog, Cat, Badger etc that need all the properties included with the Animal class plus some of their own properties unique to themselves.

This would be done by :-

Create a Superclass called ANIMAL
class Animal {
   constructor(name, howManyLegs, nocturnal) {
      ...code for properties in here...
   }
   ...code for methods in here...
}

Then you would create your SUBCLASS called Dog...
class Dog extends Animal {
   constructor(name, howManyLegs, nocturnal, walks) {
         
NOTE...When including the properties in ANIMAL you have to refer to them with 'super(...)'
AND they MUST be entered BEFORE you include properties unique to this subclass.

         super(name, howManyLegs, nocturnal);
         this._walks = walks;
   }
   ...Add any methods that are NOT already in the Animal class here...
   ...for instance 'get walks() {...}
}


Inheritance continued...


The SUPERCLASS looks just like a normal class and, therefore, could be used just like a normal class as well as a Superclass.

When you want a class to INHERIT from another class you need to include the command extends ClassName on the line where you create the Subclass (see previous pane on the left).

********************

And (in the constructor) you also need to include all the properties (that you need to pass the parameters in for) that you want to use from the Superclass as well as any additional ones you want to add to your Subclass. Eg...
constructor(name, howManyLegs, nocturnal, walks) {...}

(name, howManyLegs, nocturnal are in the ANIMAL Superclass - and walks is the new property just for use in the new Subclass)

********************

Then in the list of properties you have to FIRST of all list ALL the properties you are using from the Superclass (defined by the SUPER keyword) followed by any other properties unique to this subclass you are creating. Eg...
         super(name, howManyLegs, nocturnal);
         this._walks = walks;
   }



I have a form that uses CLASSES that you can take a look at.

It uses a main MEDIA CLASS and then has SUB CLASSES that inherits properties and Methods from the MEDIA class.

It runs from the Main Menu and is listed as Task (classes) - Books And Stuff

There are also PROTOTYPES that are used with INHERITANCE in Javascript

So far this course does not teach you about them but you can read about it HERE.

Top