Please enable Javascript to correctly display the contents on Dot Net Tricks!

Defining Namespace or Nested Objects in JavaScript

  Author : Shailendra Chauhan
Updated On : 30 Aug 2014
Total Views : 8,835   
 

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.

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri 6:30 AM-7:30 AM IST

Know More
3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (09:30 AM-11:00 AM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+