Overview

What are Classes?

  • As we have discussed earlier in the course, in JavaScript, objects are oftentimes used to represent (or model) real world items

  • Here’s an example of using an object to represent a car:

  const myCar = {
    make: 'Honda',
    model: 'Accord',
    color: 'blue',
    year: 2015
  }

  console.log(myHonda.make)
  console.log(myHonda.model)
  console.log(myHonda.color)

  // change color
  myHonda.color = `blue`  

  console.log(myHonda.color)
  
  • In practice, we often need to create many objects of the same kind, like cars, or users or whatever

  • Classes are a tool that developers use to quickly produce similar objects


Example - Creating a Car class

  • If we were creating an application for a used car dealership that needed to keep track of many cars, we could use “classes” to help us quickly produce cars within our program

  • Here’s what that class might look like:

  // define Car class
  class Car {
    constructor(make, model, color, year) {
      this._make = make
      this._model = model
      this._color = color
      this._year = year
    }

    get make() {
      return this._make
    }

    get model() {
      return this._model
    }

    get color() {
      return this._color
    }

    get year () {
      return this._year
    }

    set model (newModel) {
      this._model = newModel
    }

    set color (newColor) {
      this._color = newColor
    }
  }

  // create new "cars" using the Car class as a blueprint
  const myHonda = new Car('Honda', 'Accord', 'gray', '2017')

  console.log(myHonda.make)
  console.log(myHonda.model)
  console.log(myHonda.color)

  // change color
  myHonda.color = `blue`  

  console.log(myHonda.color)
  

JS Bin on jsbin.com

Compare our Car class with our earlier car object example. Note the similarities and the differences. We’ll discuss those differences in the upcoming sections