kaniosrn-j
7/22/2017 - 8:42 AM

Classes in ES5 and ES6

Classes in ES5 and ES6


/* ES5 - Classes
******************************************************/
var Person5 = function(name, yearOfBirth, job){
    this.name = name
    this.yearOfBirth = yearOfBirth
    this.job = job
  }
  Person5.prototype.calculateAge = function(){
    var age = (new Date().getFullYear() - this.yearOfBirth)
    console.log(age)
  }
  var person5 = new Person5('Joe', 1986, 'Front end developer')

// ES5 - Inheritance
  var Athelete5 = function(name, yearOfBirth, job, olymicGame, medals){
    // this keyword will point to an empty object
    //call method, this will be invoked only when we create an instance of Athlete5 such as in my line of code above. The Athlete5 function constructor will run, and the first thing it does is call the Person5 function constructor with the ‘this’ keyword set to our newly created Athlete5 object, which we have called john .
    Person5.call(this, name, yearOfBirth, job)
    this.olymicGame = olymicGame;
    this.medals = medals;
  }

  // Object.create allows you to manually set the prototype of an object.
  // In this case you want a prototype of Athelete5 to be a prototype of Person5 so this they will become connected
  Athelete5.prototype = Object.create(Person5.prototype)

  Athelete5.prototype.wonMedal = function(){
    this.medals ++
    console.log(this.medals);
  }

  var johnAthelete5 = new Athelete5('Joe', 1986, 'Web Developer', 5, 8)
      johnAthelete5.calculateAge()
      johnAthelete5.wonMedal()


/* ES6 - Classes
******************************************************/
  class Person6{
    constructor(name, yearOfBirth, job){
      this.name = name
      this.yearOfBirth = yearOfBirth
      this.job = job
    }
    calculateAge(){
      let age = (new Date().getFullYear() - this.yearOfBirth)
      console.log(age)
    }

    // static functionsta - usually use this as a helper function
    static greeting(){
    console.log('Hey, There!')
  }
}
  let person6 = new Person6('Joe', 1986, 'Front end developer')

  // callin static function
  Person6.greeting()

  class Athelete6 extends Person6{
    // With function constructors, you will need to repeat Person6 properties if you want them on johnAthelete6
    constructor(name, yearOfBirth, job, olymicGame, medals){
      super(name, yearOfBirth, job) //these are the constructors of Person6 class
      this.olymicGame = olymicGame
      this.medals = medals
    }

    wonMedal(){
      this.medals ++
      console.log(this.medals);
    }
  }

  const johnAthelete6 = new Athelete6('John', 1990, 'Swimmer', 5, 28)
      johnAthelete6.calculateAge()
      johnAthelete6.wonMedal()