Thursday, March 9, 2017

ES6 Classes and Extending Classes

1.class declaration

class Dog { //No paratheses after Dog

constructor(name,breed){
this.name=name;
this.breed=breed;
//Notice how we did not have to create const name and const breed

} //no comma here
//I repeat.. no comma after the function, just add on a new function below
bark(){
console.log(“Bark!”);
}
cuddle(){
console.log(“Love you owner”);
}
static info(){   //static method.
/*
Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility functions.
*/
console.log(“Dogs are nice”);
}
//getter 
//A getter is not a method. It is a property
get description(){
return(`${this.name} is breed ${this.breed}`);
}
//This getter would be called as dogObjectVariable.description;
//setter
set nicknames(value){
this.nick = value.trim(); //removes whitespaces
/*Setter note
Accessing the property setter by its own name inside the setter creates an infinite recursive function call.
So 
set nickname(valule){
this.nickname=value.trim();
would call setter nickname which calls setter nickname recursively causing a stack overflow
}
*/
}
//This setter would be set as dogObjectVariable.nicknames = "Snicky";
//getter for nicknames
get nicknames(){
return this.nick.toUpperCase(); 
}

}


const scooby = new Dog(“Scooby”,”Beagle”);


2.class expression

const Dog = class {

}

3.Extending classes and super

  class Animal {
    constructor(name) {
      this.name = name;
      this.thirst = 100;
      this.belly = [];
    }
    drink() {
      this.thirst -= 10;
      return this.thirst;
    }
    eat(food) {
      this.belly.push(food);
      return this.belly;
    }
  }

  class Dog extends Animal {
    constructor(name, breed) {
      super(name); //super initializes the class that this class is based off of
      this.breed = breed;
    }
    bark() {
      console.log('Bark bark I\'m a dog');
    }
  }

  const rhino = new Animal('Rhiney');
  const snickers = new Dog('Snickers', 'King Charles');

4.Extending arrays
We can create our own classes that are based on arrays.

  class MovieCollection extends Array {
    constructor(name, ...items) {
      super(...items);
      this.name = name;
    }
    add(movie) {
      this.push(movie);
    }
    topRated(limit = 10) {
      return this.sort((a, b) => (a.stars > b.stars ? -1 : 1)).slice(0, limit);
    }
  }

  const movies = new MovieCollection('Wes\'s Fav Movies',
    { name: 'Bee Movie', stars: 10 },
    { name: 'Star Wars Trek', stars: 1 },
    { name: 'Virgin Suicides', stars: 7 },
    { name: 'King of the Road', stars: 8 }
  );

  movies.add({ name: 'Titanic', stars: 5 });


*Whenever you extend a class, you need to create the thing that you’re extending first before you create a class of what you want. Just  call:
super();

*for…of loop only loops over iterable items

No comments:

Post a Comment