Prevent naming conflicts in JavaScript

This post is continuation of the series of posts on Modular approach in JavaScript

JavaScript based applications have taken the lead in web applications development. Web applications development using JavaScript comes with many challenges and one of them is the naming conflict. For a newbie, who does not know how to implement certain design patterns in JavaScript, preventing the naming conflict and keeping the application flexible and easy to grow is just like a nightmare.

For example, I have to define Parser function for different type of strings.

One way is to define a single parser and pass the type as parameter; parse the string based on the type using switch/if statements within the function.

Second approach could be to have a type as prefix for the function like

type1_parser();
type2_parser();

But both of the above approaches will make my code complex and difficult to use in a large application.

To solve the issue, here is one of the many approaches to prevent the naming conflict when your application is not based on any framework.

Using this approach I can add more function to the Parser namespace. I can further extend this as

Now, you will notice in above example that I have not used anything new but the JSON convention to write my code. This way I was able to prevent the naming conflict.

Now I can define many objects within other object required by the application.

Comments