Friday 19 October 2018

JavaScript: Define class using class expressions

You can define a class using class expression also.

Syntax
var/let ClassName = class {
         //Class Body
}

var/let ClassName = class ClazzName{
         //Class Body
}

Exmaple 1:
var Employee = class {
  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

HelloWorld.js
var Employee = class {
  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

function print_employee_info(emp){
  console.log("id : " + emp.id);
  console.log("firstName : " + emp.firstName);
  console.log("lastName : " + emp.lastName);
}

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

print_employee_info(emp1);

Example 2
var Employee = class MyEmployee{
  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
}


HelloWorld.js
var Employee = class MyEmployee{
  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

function print_employee_info(emp){
  console.log("id : " + emp.id);
  console.log("firstName : " + emp.firstName);
  console.log("lastName : " + emp.lastName);
}

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

print_employee_info(emp1);


Previous                                                 Next                                                 Home

No comments:

Post a Comment