Constructor

Constructor

  • JavaScript calls the constructor() method every time it creates a new instance of a class (using the new keyword)
  // define Car class
  class Car {
    constructor(make, model) {
      this._make = make
      this._model = model
    }
  }
  
  • Car is the name of our class; by convention, we capitalize and CamelCase class names

  • JavaScript will invoke the constructor() method every time we create a new instance of our Car class

  • This constructor() method accepts two parameters, make and model

  • Inside of the constructor() method, we use the this keyword; in the context of a class, this refers to an instance of that class

  • In the Car class, we use this to set the value of the Car instance’s make property (this._make) and to the make parameter and the instance’s model property (this._model) to the model parameter

Think of a Class as a blueprint and think of a instance as something that is made from that blueprint


Exercise

  • Create an class called Cat and inside that class create a constructor() that accepts two parameters: name and breed

  • Inside the constructor() method, create _name and _breed properties and sent them equal to your parameters

JS Bin on jsbin.com