5 Minute JavaScript #6 Namespaces

Last post we noticed that variables can easily be attached to the global scope. This isn’t a good thing. The more variables are linked to the global scope the more chance you have creating conflicts.

A great way to reduce the impact of your code on the global object is to define namespaces. We do this by creating one global object that we extend with extra modules which on their turn can be extended with new functionality and properties.

// Initialize this first before any other code
var Application = {};

// might be in another file for example module1.js
Application.module1 = {
	calculate: function () {},
	redirectTo: function () {}

// might be in another file for example module2.js
Application.module2 = {
	calculate: function () {},
	doSomething: function () {}

// In application

By defining the Application namespace (and the two module ‘packages’) we have no conflict between the two difference calculate functions. We also know at all times what function we are calling from which subproject or module.

This is a first step into creating frameworks, but it’s not the best solution. Most daily JavaScript users know this pattern and are using it to reduce conflicts. However, we know that in JavaScript functions are very important, so maybe we are able to improve this solution by throwing in some functions?


One thought on “5 Minute JavaScript #6 Namespaces

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

About Arvraepe