Here is a way to create class in Javascript

By xngo on February 26, 2019

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
 
      /**
       * Here is a way to create class in Javascript. There are many other ways.
       * Note: I explicitly omit to show private members as it is getting complicated.
       *        For simplicity, stick with the public members. 
       *        For more info, see http://javascript.crockford.com/private.html
       */
 
      // Employee class
      function Employee(sName)
      {
        // Public variables.
        this.name = sName;
        this.iWorkHours = 5;
      }
 
      // Implementation of functions.
      Employee.prototype.addWorkHours = function(iHours)
      {
        this.iWorkHours += iHours;
      }
 
      Employee.prototype.getWorkHours = function()
      {
        return this.iWorkHours;
      }
 
      // Create Employee object.
      var emplA = new Employee();
 
      // Direct access to public variable.
      emplA.name="Xuan Ngo";
 
      // Calling function.
      emplA.addWorkHours(10);
 
      // Display the results.
      window.alert(emplA.name+ ' worked for ' +emplA.getWorkHours()+ ' hrs.');
    </script>
 
    <title>Class example</title>
  </head>
 
  <body>
  </body>
</html>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.