Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active January 28, 2020 16:39
Show Gist options
  • Save ross-u/00ec284364c10cae0c099c3cfd3530a7 to your computer and use it in GitHub Desktop.
Save ross-u/00ec284364c10cae0c099c3cfd3530a7 to your computer and use it in GitHub Desktop.
JS | ES 6 - Classes and Species - Exercise

JS | ES 6 - recap


Classes and Species - Exercise



For this exercise you can use Repl.it or your code editor.

Complete the below file steps as specified in the task list.


Task 1

Fish, mammals, amphibians, reptiles, and birds are separate categories / types of vertebrate animals (animals that possess a spine).

Using the ES6 syntax create a class Animal, which creates object instances with a property type.

class Animal constructor should take one parameter - type. The Animal class should have a method on the prototype (created using ES6 syntax) called animalType which console logs the type .


class Animal {
  // Your code here ...
}

// Animal.prototype.animalType   <-- Wrong, use ES6 syntax to create the method on the prototype 

let bear = new Animal('mammal');
let snake = new Animal('reptile');

bear.animalType();  	// Expected Output:  "mammal"
snake.animalType(); 	// Expected Output:  "reptile"

Task 2

Using ES6 syntax create additional class Cat, which extends Animal, and creates object instances with properties type, species, petName and color.

As every cat is a mammal (obviously cat can't be a fish), property type must be created by calling the parent class using super, and passing it a value 'mammal', like this: super('mammal');.

As every cat belongs to the cat species, we don't want to use the constructor to pass the value for the species property (we will exclude it from the constructor parameters).

Instead species property should be hard coded a default string value 'cat' (given directly a.k.a. imperatively ).

Cat class should have a method on the prototype (using ES6 syntax) named meow which console logs ${petName} says: meow.


class Cat extends Animal {
  // Your code here ...
}


let sparky = new Cat('sparky', 'gray');

sparky.meow();  //  Expected Output:  "sparky says: meow"
sparky.animalType();  // Expected Output:  "mammal"

Task 3

Following the same pattern for the class Cat, create another class Dog. The Dog class should have a property species set by default to 'Dog' and a method woof created on the prototype (using ES6 syntax) which console logs ${petName} says: woof.

class Dog extends Animal {
    // Your code here ...
}

let rocket = new Dog('rocket', 'white');

rocket.woof();  //  Expected Output:  "rocket says: woof! "
rocket.animalType();  // Expected Output:  "mammal"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment