Demonstrate namespace and access to Javascript object

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">
 
      var MyNamespace = {}; // Create a namespace.
      MyNamespace.NumberOfEmployees = 0; // Global variable of the namespace.
 
      // Employee class
      MyNamespace.Employee = function(sName)
      {
        this.name = sName;
        this.iWorkHours = 5;
 
        MyNamespace.NumberOfEmployees++; // Show the use of global variable of the namespace.
      };
 
      // Implementation of functions.
      MyNamespace.Employee.prototype.addWorkHours = function(iHours)
      {
        this.iWorkHours += iHours;
      };
 
      MyNamespace.Employee.prototype.getWorkHours = function()
      {
        return this.iWorkHours;
      };
 
      // Create Employee objects.
      var emplA = new MyNamespace.Employee();
      var emplB = new MyNamespace.Employee('John Smith');
 
      // Access public variable.
      emplA.name="Xuan Ngo";
 
      // Calling function.
      emplA.addWorkHours(10);
      emplB.addWorkHours(30);
 
      window.alert( emplA.name+ ' worked for ' +emplA.getWorkHours()+ " hrs.\n"+
                    emplB.name+ ' worked for ' +emplB.getWorkHours()+ " hrs.\n"+
                    'There are ' + MyNamespace.NumberOfEmployees + ' employees.'
                    );
 
    </script>
 
    <title>Namespace and 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.