Saturday 20 October 2018

JavaScript: Adding prototype properties to a class

You can add prototype properties to a class using below syntax.

Syntax
ClassName.prototype.propertyName

Example
Employee.prototype.organization="ABC Corporation";

HelloWorld.js
class Employee{
  constructor(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
    Employee.noOfEmployees++;
  }
  
  static printEmployeeInfo(emp){
    console.log("\n************************");
    console.log("firstName : " + emp.firstName);
    console.log("lastName : " + emp.lastName);
    console.log("Organization : " + emp.organization);
  }
}


Employee.noOfEmployees = 0;
Employee.prototype.organization="ABC Corporation";

var emp1 = new Employee("Krishna", "Gurram");
var emp2 = new Employee("Gopi", "Battu");

Employee.printEmployeeInfo(emp1);
Employee.printEmployeeInfo(emp2);

emp1.organization = "XYZ Corp";
emp2.organization = "BBC Corp";

Employee.printEmployeeInfo(emp1);
Employee.printEmployeeInfo(emp2);


Output

************************
firstName : Krishna
lastName : Gurram
Organization : ABC Corporation

************************
firstName : Gopi
lastName : Battu
Organization : ABC Corporation

************************
firstName : Krishna
lastName : Gurram
Organization : XYZ Corp

************************
firstName : Gopi
lastName : Battu
Organization : BBC Corp




Previous                                                 Next                                                 Home

No comments:

Post a Comment