Topic Review - learn-co-curriculum/js-oo-introduction GitHub Wiki

Objectives

Use and understand the difference between object constructors and prototypes in Javascript.

Setup

Start with the constructor for Bike and Owner already stubbed out.

function Owner (name) {
  this.name = name;
}

function Bike (name, type, color) {
  this.name = name;
  this.bikeType = type;
  this.frameColor = color;
}

Overview

The goal of this topic review to practice when to use constructors to define properties and when to use the prototype. Methods or properties which are shared across all instances should be attached to the prototype. Why? Because this allows us to load that definition into memory only once.

Start by adding a condition to our bike. Each bike should be initialized with a condition of "ready to go!" Should this be on the prototype or the constructor? The constructor! Why? Because not all bikes share one condition - each bike has it's own condition, even if they initialize the same.

Point out, however, that WHEELS is a constant shared by all of our Bike objects - this can be attached to the prototype.

function Bike (name, type, color) {
  this.name = name;
  this.bikeType = type;
  this.frameColor = color;
  this.condition = "ready to go";
}

Bike.prototype.WHEELS = 2;

We can now add methods to give our Bike object abilities. Each new instance will share the same function definition - we'll add these to the prototype.

Bike.prototype.takeForARide = function(miles){
  if (miles > 50) {
    this.condition = 'needs a tune up';
  }
};

Bike.prototype.tuneUp = function(){
  if (this.condition == 'needs a tune up'){
    this.condition = 'ready to go!';
  }
};

Bike.prototype.WHEELS = 2;

Copy the above code into the Javascript Console. Create a new instance of a bike. Show the return value of WHEELS.

var bike = new Bike("Daria", "Mountain Bike", "Green");
bike.WHEELS
> 2

Now, change the number of WHEELS on our bike.

Bike.prototype.WHEELS = 3; 

What will bike.WHEELS return now? If it returns 2, this means that the value of WHEELS was assigned when on bike was initialized. If it's 3, it means that it loads it dynamically from our prototype.

bike.WHEELS
> 3