JavaScript Namespaces

Petr Kostelanský | 21 October 2017
The best approach to create code structure is by using namespaces. In JavaScript namespacing is achieved by Module Pattern.

Basically Module Pattern is based on Closures. So, let's look at an example how create module (namespace) that will reveal two object definitions:

var MyNamespace1 = (function () {
    function Person(name) {
        this.name = name;
    };
    Person.prototype = {
        getName: function () {
            return this.name;
        }
    };
    
    function Employee(name, salary) {
        Person.call(this, name);
        this.salary = salary;
    }
    Employee.prototype = Object.create(Person.prototype);
    Employee.prototype.constructor = Employee;
    Employee.prototype = {
        getSalary: function () {
            return this.salary;
        }
    };
   
    return {
        Person: Person,
        Employee: Employee
    };
}());

var steve = new MyNamespace1.Person('Steve');
alert(steve.getName());

var todd = new MyNamespace1.Employee('Todd', 200);
alert(todd.getSalary());

Thank to closures we can't accessed Person directly but just by using name of module (namespace) MyNamespace1 and we are protected from using another Person class with the same name. This is very useful approach how clearly define which object we are creating because we use namespace. 

Loading ads...