Saturday, 20 October 2018

JavaScript: Adding getter and setter methods to class

You can add getter and setter methods to a class.

For example, I added fullName method.
get fullName(): It returns the full name by appending lastName to firstName.
set fullName(name): Sets firstName, lastName based on the name.

var Employee = class MyEmployee{
  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
 
  get fullName(){
    return this.firstName + "," + this.lastName;
  }
 
  /*firstName and lastName are set based on given name*/
  set fullName(name){
    var names = name.toString().split(",");
    this.firstName = names[0];
    this.lastName = names[1];
  }

}

Find the below working example.

HelloWorld.js

var Employee = class MyEmployee{
  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  print_employee_info(){
    console.log("id : " + this.id);
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
    console.log("fullName : " + this.fullName);
  }
  
  get fullName(){
    return this.firstName + "," + this.lastName;
  }
  
  /*firstName and lastName are set based on given name*/
  set fullName(name){
    var names = name.toString().split(",");
    this.firstName = names[0];
    this.lastName = names[1];
  }

}

var emp1 = new Employee(1, "Krishna", "maj");
emp1.print_employee_info();

emp1.fullName = "Ram,Gurram";
emp1.print_employee_info();

Output
id : 1
firstName : Krishna
lastName : maj
fullName : Krishna,maj
id : 1
firstName : Ram
lastName : Gurram
fullName : Ram,Gurram


Previous                                                 Next                                                 Home

No comments:

Post a Comment