Skip to content
Related Articles

Related Articles

Namespacing in JavaScript

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Feb, 2021
View Discussion
Improve Article
Save Article

JavaScript by default lacks namespaces however, we can use objects to create namespaces. A nested namespace is a namespace inside another namespace. In JavaScript, we can define a nested namespace by creating an object inside another object.

JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

Example: An HTML file, in which we are calling two JavaScript files, namespace1.js, and namespace2.js where.

  • namespace1.js Handling an event of changing the background color to ‘yellow’ and text color to ‘grey’ on pointing the mouse pointer to the <div> element.

  • namespace2.js Handling an event of changing the background color to ‘pink’ and text color to ‘charcoal’ on moving the mouse pointer away from the <div> element.

HTML




<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8" />
  <title>Namespacing in JavaScript</title>
 </head>
 <body>
    <div id="output">This is the div</div>
  
    <script src="./namespace1.js"></script>
    <script src="./namespace2.js"></script>
 </body>
</html>


namespace1.js




let MAC = {
    colorDiv: function(ev){
        let target = ev.currentTarget;
        target.style.backgroundColor = 'yellow';
        target.style.color = '#808080';
    }, 
    init: function(){
        let divA = document.getElementById('output');
        divA.addEventListener('mouseover',
        MAC.colorDiv);
    }
}
  
MAC.init();


namespace2.js




let WIN = {
    colorDiv: function(ev){
        let target = ev.currentTarget;
        target.style.backgroundColor = 'pink';
        target.style.color = '#36454F';
    }, 
    init: function(){
        let divB = document.getElementById('output');
        divB.addEventListener('mouseout',
        this.colorDiv);
    }
}
  
WIN.init();


Output:

  • On pointing the mouse pointer to the <div> element.

  • On moving the mouse pointer away from the <div> element.

If namespaces are not used then there occurs an error of using the same function in two or more JavaScript files because functions in JavaScript are declared globally. In our case, ‘colorDiv’ function is used both in namespace1.js and namespace2.js. If namespaces are not used in the above example then it will throw an error: “Uncaught SyntaxError: Identifier ‘colorDiv’ has already been declared at namespace2.js”.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!