An Introduction to JavaScript Classes & Methods
Tags: javascript, classes, objects, methods
Published: 2020-05-21 17:01:37


# JavaScript Classes 

In programming, classes are used a "blue print" for modeling real-world items in code. 

In JavaScript, the syntax for creating a class could be as simple as: 

```js 
class Square {
    constructor(sideLength){
        this.sideLength = sideLength; 
    }
    area(){
        return this.sideLength * this.sideLength; 
    }
}
```
## Breaking this down:

1. First we declared a `class` called `Square` to represent the idea of a square. 

2. Then we declared that in order to create a square, we need to know the length of one side of the square. We specified this by defining a `constructor` method, which is a special method that "builds" our class when we instantiate it. 

3. In the `constructor` we took the provided `sideLength` and saved it to an instance variable called: `sideLength` 
    a. Variables specified with the keyword `this` indicate instance variables 

4. We also specified a method called `area` which takes no parameters/arguments, as denoted by the empty parenthesis `area()`. In this method, we specified that the area of the `Square` is equal to `this.sideLength * this.sideLength` 

## Instantiating 

Once the blue print (`class`) has been defined, we create "instances" or specific occurences of that class. In order to instantiate the class we defined above we would use the following syntax: 
```js
let square = new Square(5); 
```
This says, store an instance of a square, with a `sideLength` equal to `5` in a variable we named `square`. Now that we have an instance we can use the instance method associated with the `Square` class: 
```js
square.area(); // => 25 
```

## Methods Types 

### Standard Methods 

Recall the `Square` class example... 
```js 
class Square {
    constructor(sideLength){
        this.sideLength = sideLength; 
    }
    area(){
        return this.sideLength * this.sideLength; 
    }
}
```
... `area()` is a standard class method. Standard methods in JavaScript are available to any instance of the class they to which they are defined. 

### Static Methods 

Static methods are class-level methods. In other words, they cannot be called on an instance of a class, but rather they are called on the class itself. Typically, static methods are generic utility methods that have functionality relating to the class, but not an instance of a class. 

To illustrate this, we will use a different example: 

```js
class MyMath {
    static square(number){
        return number * number; 
    }
    static cube(number){
        return number * number * number; 
    }
}
```

In the example above, we are defining what it means to `square` a number, and what it means to `cube` a number. It is important to note, that with static methods, we have no dependence on an instance - or in more technical terms; static methods are stateless. 

To use a static method, we must call upon the method at the class level, **not** the instance level: 

```js
let squaredNumber = MyMath.square(5);  // => 25 
let cubedNumber = MyMath.cube(3) // => 9 
```

### Getters and Setters 

In most object-oriented programming (OOP) languages, objects/classes have "getter" and "setter" methods that provide access to instance variables. In most native OOP languages, you have "private variables" that are only accessible within the class themselves. This is designed to protect the state of that object by controlling when and how instance variables are set ("setters") and retrieved ("getters"). 

JavaScript is a functional programming language at its core, which means that it is designed to be written in a procedural style. This is in comparison to OOP languages which model "state" (variables) and "behavior" (methods) within objects after real life. Diving into procedural vs. OOP is out of scope for this topic, but a fundamental programming idea that every modern developer should have a firm grasp around. 

```js
class Dog {
    constructor(name){
        this.name = name; 
        this._activityLevel = 1; 
    }
    // setter method 
    set activityLevel(level){
        if (level > 10) level = 10 
        if (level < 1) level = 1 
        this._activityLevel = level; 
    }
    // getter method 
    get run(){
        return `${name} runs ${this._activityLevel * 1.2} miles per day`  
    }
}
```

Inherently, "getter" methods (in JavaScript) provide the ability to access an objects internal state, without invoking the method: 

```js
let skipTheDog = new Dog("Skip");   // => null 
skipTheDog.activityLevel(5);        // => null 
skipTheDog.run;                     // => `Skip runs 6 miles per day`  
```

Notice with the setter (`skipTheDog.activityLevel(5);`), we pass in the value we want to use to modify the internal state of the object. Conversely, with getter we do not need to use parenthesis (`()`) or "invoke" the method as it is defined as a "getter" method in the class definition. In other words; "getter" methods operate a lot like the properties of an object, except that they do not allow you to change the objects internal state: 

```js
let skipTheDog = new Dog("Skip");                // => null 
skipTheDog.activityLevel(5);                     // => null 
skipTheDog.run = `Skip runs six miles per day`   // => ERROR 
```

Per the example above, we can not use "getter" methods to set internal state, so this would throw an error. 


# Glossary of Terms 

* **Class** - a blue-print that defines a type of object. 
* **Constructor** - a special method that defines the required parameters to instantiate that class. 
* **Instance** - A specific occurance of an instantiated class. 
* **Instantiation** - The process of creating an "instance" of a class 
* **Invoke** - to call execution of a method, function, subroutine or procedure 
* **Method** - a procedure associated with a class that defines behavior of an object 
* **Parameter** - an arguement for a method