Questions And Answers

More Tutorials

Javascript Namespacing

Namespace by direct assignment

antipattern 3 global variables

var setActivePage = function () {};
 var getPage = function() {};
 var redirectPage = function() {};

just 1 global variable, no function collision and more meaningful function names

var NavigationNs = NavigationNs || {}; = function() {}
 NavigationNs.pagination = function() {}
 NavigationNs.redirection = function() {}

Nested Namespaces

When multiple modules are involved, avoid proliferating global names by creating a single global namespace. From there, any sub-modules can be added to the global namespace. (Further nesting will slow down performance and add unnecessary complexity.) Longer names can be used if name clashes are an issue:

var NavigationNs = NavigationNs || {}; = {};
 NavigationNs.pagination = {};
 NavigationNs.redirection = {};

 // The second level start here.
 Navigational.pagination.jquery = function();
 Navigational.pagination.angular = function();
 Navigational.pagination.ember = function();

Context (this)

var person = {
 name: 'John Doe',
 age: 42,
 gender: 'male',
 bio: function() {
 console.log('My name is ' +;
var bio =;


"My name is John Doe"
"My name is undefined"

In the above code, makes use of the context (this). When the function is called as, the context gets passed automatically, and so it correctly logs "My name is John Doe". When assigning the function to a variable though, it loses its context.

In non-strict mode, the default context is the global object (window). In strict mode it is undefined.

this in constructor functions

When using a function as a constructor, it has a special this binding, which refers to the newly created object:

function Cat(name) { = name;
 this.sound = "Meow";
var cat = new Cat("Tom"); 
var cat2 = Cat("Tom");;; // error! cannot access property of undefined




In this page (written and validated by ) you learned about Javascript Namespacing . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Setters and Getters.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.