First let us understand why we need namespaces in JavaScript.
Before reading this article, you may want to go through the following articles:
In JavaScript there are the following two flavors of the scope of a variable:
- Global if defined outside any function
- Local to the function and all nested functions, if defined in the function
So if a variable is not defined inside a function then its scope is throughout JavaScript program. This could cause problems if you want to use a JavaScript program in another JavaScript program or may cross webpages. There is no way in the JavaScript scope of a variable that can be restricted to a block of code.
This can be done by using a function as a namespace in JavaScript. Essentially, to create a JavaScript namespace, you need to put all code of the JavaScript program in a JavaScript function.
A namespace can be created as in the following:
You see, to create a namespace you need an opening parenthesis and then put a function inside that as shown in the image above. Now every variable you define under this function will have the scope in this block of code only.
The other way you can create a Namespace is as given below:
Essentially a namespace can be created in JavaScript as follows:
<script type="text/javascript" >
var MyModule = {
//code for module here
GetData: function() {
var student =
{
name: "dj",
grade: 10
};
var nameisobjectofstudent = "toString" in student;
alert(nameisobjectofstudent);
}
};
</script>
And you can execute the GetData() function as follows.
In this way you can work with namespaces in JavaScript. I hope you find this article useful. Thanks for reading.