Topic Review - learn-co-curriculum/dog.js GitHub Wiki

Objectives

  1. Assign properties to an object using a constructor.
  2. Define methods using the prototype.

Setup

This is a short lab - simply have the lab forked and cloned and you'll be ready to go. As you build, it may be helpful to build out the equivalent Dog class in Ruby.

Overview

To begin, we have the following code stubbed out - a constructor for Dog and some methods assigned to the prototype.

function Dog(/* args go here */){
  // assign the name and age properties here
}

Dog.prototype.ageInYears = function() {
};

Dog.prototype.ageInDays = function() {
};

Dog.prototype.ageInDogYears = function() {
};

We're building towards an interface where we could create a new instances of Dogs so that each one has an individual name and age.

var fido = new Dog("Fido", 7)
fido.name
> "Fido"
fido.age
> 7

We also should be able to call methods on the instance, the same way we do in Ruby. Here's the same stubbed out Dog class in Ruby instead of JS.

class Dog
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def age_in_years
    self.age
  end

  def age_in_days
    self.age * 365
  end

  def age_in_dog_years
    self.age * 7
  end

First, let's assign the dog's name and age at initialization.

function Dog(name, age){
  this.name = name;
  this.age = age;
}

Now, we can define our methods attached to the prototype. ASK QUESION - why can't we just define those methods as part of the constructor? ANSWER Because then we'd be loading a new function definition for each instance of our Dog object. Using the prototype, all dogs can share one function definition.

function Dog(name, age){
  this.name = name;
  this.age = age;
}

Dog.prototype.ageInYears = function() {
  return this.age;
};

Dog.prototype.ageInDays = function() {
  return this.age * 365;
};

Dog.prototype.ageInDogYears = function() {
  return this.age * 7;
};

BONUS / ALTERNATIVE

Instead of/addition to building out a Dog object, build out a User object to represent Facebook's user class.

var User = function(name, age) {
  this.name = name;
  this.age = age;
  this.friends = [];
  this.poke_count = 0;
};

User.prototype.getPoked = function() {
  this.poke_count ++;
}

User.prototype.pokeFriend = function(friend) {
  friend.getPoked();
}