Namespace Pattern
Namespace can dramatically reduce the number of globals required and at the same time prevents the collisions or excessive name prefixing .
Its important to know that javascript doesn't have namespaces built into the language syntax , but you can achieve this feature quite easy .Instead of adding functions,objects and variables into global scope you can create one global object and add all the functionality
Refactor anti-pattern to Namespace example
Consider this example
//anti-pattern example
function Read() {}
function Speak() {}
var topic_to_learn = "Javascript";
//objects
var book1 = {}
book1.data = {title:"Learn javascript",author:"John doe"}
var book2 = {};
in this example all the functions,variables and objects are declared and polluting the global scope of your application . You can refactor this type of code by creating a single global object for your application , called for example Student and change all functions and variables to become properties of your global object
//Declare the global object
var STUDENT = {}
//constructors
STUDENT.Read = function(){};
STUDENT.SPEAK = function(){};
//a varibale
STUDENT.topic_to_learn = "javascript"
//object container
STUDENT.books = {}
//nested objects
STUDENT.books.book1 = {};
STUDENT.books.book1.data = {title:"Learn javascript",author:"John doe"}
//add second book
STUDENT.books.book2 = {};
This pattern is good way to namespace your code and avoid naming collisions not only in your own code but collisions between your code and third-party code on the same page .
Drawbacks of Namespace
- More to type , prefixing every variable and function adds up in the total amount of code that needs to be downloaded
- Only one global instance as a result any part of the code can modify the global instance and the rest of the functionality gets the updated state
- Long nested names = slower property resolution lookups
Top comments (1)
Or use modules