JavaScript add namespace

In the given example, we have created two objects Util and Coll.

JavaScript add namespace


In this section, we are going to create the namespace using the JavaScript.

In the given example, we have created two objects Util and Coll. By creating the objects for each namespace, we can add the functions as methods to these objects. Here we have added the functions add() and sub() to the Util object. And the functions mul() and div() to the Coll object. By using Util.add(), Util.sub(), Coll.mul() and Coll.div(), we can call the methods globally on the page as we have done here





Here is the code:

<h2>Use of Namespaces</h2>
var Util = {
add: function() {
alert("This is addition method.");
sub: function() {
alert("This is subtraction method.");
var Coll = {
mul: function() {
alert("This is multiplication method.");
div: function() {
alert("This is division method.");
<input type="button" onClick="Util.add();" value='Add'>
<input type="button" onClick="Util.sub();" value='Subtract'>
<input type="button" onClick="Coll.mul();" value='Multiply'>
<input type="button" onClick="Coll.div();" value='Divide'>

Output will be displayed as:

On clicking the button, you will get the alert messages.

Download Source Code:

Share on Google+Share on Google+

JavaScript add namespace

Posted on: June 12, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: JavaScript add namespace  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image