Advertisement
Even though JavaScript lacks namespaces, we can use Objects, an IIFE (Immediately Invoked Function Expression) or let/const to create namespaces.
1. Using Object Literal Notation: Let's wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object notation
1var namespaceOne = {
2 function func1() {
3 console.log("This is a first definition");
4 }
5 }
6 var namespaceTwo = {
7 function func1() {
8 console.log("This is a second definition");
9 }
10 }
11 namespaceOne.func1(); // This is a first definition
12 namespaceTwo.func1(); // This is a second definition2. Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.
1(function () {
2 function fun1() {
3 console.log("This is a first definition");
4 }
5 fun1();
6 })();
7
8 (function () {
9 function fun1() {
10 console.log("This is a second definition");
11 }
12 fun1();
13 })();3. Using a block and a let/const declaration: In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a variable to a block.
1{
2 let myFunction = function fun1() {
3 console.log("This is a first definition");
4 };
5 myFunction();
6 }
7 //myFunction(): ReferenceError: myFunction is not defined.
8
9 {
10 let myFunction = function fun1() {
11 console.log("This is a second definition");
12 };
13 myFunction();
14 }
15 //myFunction(): ReferenceError: myFunction is not defined.Advertisement
JavaScript Coding Exercise 36
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement