Sunday, December 19, 2021

Class in ES6

 //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 john5 = new person5('lokman', 1990, 'engineer');

//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);

    }

    static greetings(){

        console.log('hey there ');

    }

}

const john6 = new  Person6('lokman',1990,'engineer');

we can define static function in ES6 which will attach to a class. So we can not call it using object of the class.

Person6.greetings();

points to remember:

class definition are not hoisted unlike function constructor.



No comments:

Post a Comment

Fluent interface pattern

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