Monday, December 20, 2021

Inheritance in ES6

 First let see the example of how inheritance works in ES5.

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 Athlete5 = function(name, yearOfBirth, job, olympicGames, medals) {

    Person5.call(this, name, yearOfBirth, job);

    this.olympicGames = olympicGames;

    this.medals = medals;

}

Athlete5.prototype = Object.create(Person5.prototype); //will create new instance and point prototype of Person5                                                                                           to Athlete5. So that now we can access the prototype of                                                                                             Person5 using object of Athlete5.

var johnAthlete5 = new Athlete5('lokman', 1990, 'engineer', 'swimmer', 3);

johnAthlete5.calculateAge();

Here ,Athlete5 is inheriting Person5. 


//ES6
class Person6 {
    constructor(name, yearOfBirth, job) {
        this.name = name;
        this.yearofBirth = yearOfBirth;
        this.job = job;
    }

    calculateAge() {
        var age = new Date().getFullYear() - this.yearofBirth;
        console.log(age);
    }

}

class Athlete6 extends Person6 {
    constructor(name, yearOfBirth, job, olympicGames, medal) {
        super(name, yearOfBirth, job);
        this.olympicGames = olympicGames;
        this.medals = medal;
    }
    
    wonmedals(){
        this.wonmedals++;
        console.log(this.medals);
    }

}

const johnatlete6 = new Athlete6("john",1989,"engineer","tokyo",1);
johnatlete6.calculateAge();
johnatlete6.wonmedals();


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...