Friday 19 October 2018

JavaScript: Introduction to Classes

Classes are used to create objects. Let me try to explain with an example.

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

As you see above snippet, I defined a class Employee, which has 3 properties id, firstName, lastName.

a.   class keyword is used to create a class.
b.   constructor function is used to initialize the properties.

You can define object to the class Employee using new operator, followed by constructor function.
var emp1 = new Employee(1, "Sailaja", "PTR");

HelloWorld.js
class Employee{
  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);


Output
id : 1
firstName : Sailaja
lastName : PTR   





Previous                                                 Next                                                 Home

No comments:

Post a Comment