22
DecDefining Namespace or Nested Objects in JavaScript
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.
Read More: 50+ Javascript Interview Questions
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>
Read More: Javascript Developer Salary in India
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.
Take our Javascript skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.