Instances

Instances

  • An instance is an object that contains the property names and methods of a class, but with unique property values (i.e. instances of a Class have their own unique identities)

Example - Creating Instances

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

  // create a new instance of the Car class
  // and store it in a variable named myTesla
  const myTesla = new Car("Tesla", "Model 3")

  console.log(myTesla)
  
  • Here’s a summary of the code above:

    • Below our Class definition we are using the new keyword to create a new instance of our Car class

    • We create a new variable named myTesla that will store an instance of our Car class

    • We use new keyword to generate a new instance of the Car class

      • The new keyword calls the constructor() method of a class, runs the code inside of it and then returns a new instance
    • We pass the two strings to the Car constructor ("Tesla" and "Model 3")

      • This will set the make property to "Tesla" and the model property to "Model 3"
    • Then we log the value saved to the make property of the myTesla instance which prints out "Tesla"

JS Bin on jsbin.com


Exercise

  • Create an instance of the Cat class and set name to "Hobbes" and breed to "Tabby"; save the instance to a const variable named hobbesCat

  • Create another instance of the Cat class and set name to "Tigger" and breed to "Tiger", save the instance to a const variable named tiggerCat

  class Cat {
    constructor(name, breed) {
      this._name = name
      this._breed = breed
    }
  }
  // add your code below

  // add your code above

  console.log(hobbesCat)
  console.log(tiggerCat)
  

JS Bin on jsbin.com