Menu
Coddy logo textTech

Classes

Lesson 7 of 9 in Coddy's Tricky parts of Modern Javascript (ES6+) course.

A class is a template for creating objects

Use the keyword class to create a class.

class can have a special method with name constructor to initialize the object variables.

constructor method is executed when an object is created from class using new keyword. ex. const person = new Person("Coddy");

class Employee {

  constructor(name, id) { //constructor
    this.name = name;
    this.id = id;     
  }
  
  work(){    // a class method 
  	console.log("Employee works");
  }
}

Observe above example , class Employee is a template of object which will have two properties (variables) i.e. name, id and a method named work.

const employee1 = new Employee("John Doe", 10001) ; // provide values of name & id in constructor

console.log(employee1.name) // John Doe  - access variables

employee1.work() // "Employee works" - access methods
challenge icon

Challenge

Easy

Create a class Person which will have name and age properties and update and print methods.

The update method should take name and age parameters and should update the class properties name & age.

The print method should print the values of name and age in the format : "Person name: <name>, age: <age>"  where <name> and <age> are the values of name and age.

Ex. "Person name: Shubham, age: 25"

Don't forget the constructor to initialize the properties

Try it yourself

All lessons in Tricky parts of Modern Javascript (ES6+)