Saturday 20 October 2018

JavaScript: Adding prototype methods to class

You can add prototype methods (methods that are available to all the objects) to a class.

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

For example, I added print_employee_info method to the class Employee. Observe above snippet, I am not added function keyword (function keyword is not required) to the method print_employee_info() method.

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

var emp1 = new Employee(1, "Sailaja", "PTR");

emp1.print_employee_info();

Output
id : 1
firstName : Sailaja
lastName : PTR


Previous                                                 Next                                                 Home

No comments:

Post a Comment