Defining Namespace or Nested Objects in JavaScript

06 Sep 2022
Intermediate
2.37K Views
1 min read  

JavaScript is a dynamic language. You can create objects on the fly, and objects can contain other objects, also it does not support the concept of namespace like C#.

Basically, a namespace is like a container which contains classes. In JavaScript you can achieve the same functionality as Namespace by creating nested objects. And since window itself is an object you can actually create objects directly into it. But if we would like to create an object in a non-existent nested namespace, we'll need to create that first.

Simple Namespace
<script>
var MyNameSpace = {
 calculateVat: function (base) {
 return base * 1.21;
 },
 product: function (price) {
 this.price = price;
 this.getPrice = function () {
 return this.price;
 };
 },
 doCalculations: function () {
 var p = new MyNameSpace.product(100);
 alert(this.calculateVat(p.getPrice()));
 }
}

//instancing product class
var p = new MyNameSpace.product(150);
//calling product class method
alert(p.getPrice());
</script>

Namespaces Nesting

<script>
var MyNameSpace = {
 calculateVat: function (base) {
 return base * 1.21;
 },
 MyNameSpace2: {
 product: function (price) {
 this.price = price;
 this.getPrice = function () {
 return this.price;
 };
 }
 },
 doCalculations: function () {
 var p = new MyNameSpace.product(100);
 alert(this.calculateVat(p.getPrice()));
 }
}

//instancing product class
var p = new MyNameSpace.MyNameSpace2.product(150);
//calling product class method
alert(p.getPrice());
</script>
What do you think?

I hope you will enjoy the namespace while programming with javascript. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this