Introduction
This is the "Advanced JavaScript" article series. In this series, we have learned many beautiful concepts of JavaScript. If you are very new to this series then please have a look at the previous articles.
The following are links to all the articles.
- Advance JavaScript: History and role of JavaScript behind modern web
- Advance JavaScript: play with object in JavaScript
- Advance JavaScript: Function Definition Style in JavaScript
- Advance JavaScript: Understand undefined in JavaScript
- Advance JavaScript: Understand "class"-ical concept of JavaScript
- Advance JavaScript: Implement inheritance in JavaScript
- Advance JavaScript: Callback design pattern and callback function in JavaScript
- Advance JavaScript: Exception handling in JavaScript
- Advance JavaScript: Scope of Variable in JavaScript
- Advance JavaScript: closure in JavaScript
- Advance JavaScript: Immediate invoke function in JavaScript
In this article we will learn the concept of namespaces in JavaScript. If you are a C# developer then you might understand the concept of namespaces very well. If not then the following is a small introduction for you.
Problem without namespace
In this example, we will define two functions that will share the same name. Have a look at the following example, we have defined fun1( ) two times and then we are calling fun1() and we are seeing that the latest function is executed.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- </head>
- <body>
- <script>
- function fun1() {
- console.log("This is fun1");
- }
- function fun1() {
- console.log("This is fun2");
- }
- fun1();
- </script>
- </body>
- </html>
Here is the sample output.

As we have explained earlier, a namespace solves the name collision problem. In this example, we will share the same function name in more than one function but they will belong to different namespaces. Have a look at the following example:
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- </head>
- <body>
- <script>
- var myfunctionCollection1 = {
- fun1: function () {
- console.log("This is fun1");
- },
- fun2: function () {
- console.log("This is fun2");
- }
- }
- var myfunctionCollection2 = {
- fun1: function () {
- console.log("This is fun1");
- },
- fun2: function () {
- console.log("This is fun2");
- }
- }myfunctionCollection.fun1();
- </script>
- </body>
- </html>




Rajneesh RaiPosted Nov 27, 2013, 8:41 AM
Nice article !! but have a typo error in function call myfunctionCollection.fun1(), under "Using a namespace to solve the problem" section
Santosh KumarPosted Nov 21, 2013, 9:32 AM
Nice.