Key Takeaways
- Namespacing in JavaScript/jQuery is a crucial technique for protecting your code from being overwritten by other code. It provides encapsulation by structuring your methods/data inside a single namespace, allowing you to name your variables freely without worrying about conflicts.
- Creating a namespace involves defining an object and adding properties to it, which can be variables, functions, or even other objects. This object acts as a controller to the code, and all properties are local to that namespace. Nesting namespaces is also possible for further organization.
- Encapsulating your namespace within a self-executing jQuery function allows you to reference your objects, functions, and variables from within. This requires declaring the namespace outside the enclosing function to make it accessible from outside. An alternative method involves assigning the namespace to the window scope, which allows for encapsulation while still enabling the use of the dollar sign ($) for jQuery code.
What is namespacing?
In a nutshell, namespacing is a way to protect your code using javascript object literal notation to provide encapsulation. Minimizing your code’s footprint in this root scope by structuring your methods/data inside a single namespace should be the goal of every decent developer. The advantages are that you can name your variables whatever you like and not have to worry about some other code overwriting it’s value. In this post I’m going to show you nested object namespacing because this is the most common form of namespacing in jQuery. Ok, lets dive straight into some examples.You can paste any of these examples straight into the Firebug console to see what it does and play around with it.This is a regular way to declare a function in JavaScript.
myFunction = function()
{
console.log('running myFunction...');
};
myFunction(); //function call
Now the problem with this, is any other code could also declare a function call “myFunction” and this would overwrite yours! Not good. So what’s the solution? You guessed it, namespacing!
A basic namespace
Here is how you would create a basic namespace to protect your function:;MYNAMESPACE = {
myFunction: function()
{
console.log('running MYNAMESPACE.myFunction...');
}
}
MYNAMESPACE.myFunction(); //function call
Now, nothing can overwrite your function and everything is contained within a namespace called “MYNAMESPACE”. To call your function you simply include the namespace before the function.
Naming your space
Ok, so you have looked at the code above and wondered why the namespace is all capitals. It’s my preference to keep namespaces in capitals because they are JavaScript referenced objects, but this depends on your personal or work coding practices. It’s also a good to keep them short as possible so I probably should have called my namespace “NS” or such (This is because namespaces can get long when chained together, we’ll go through this later on in the post).A namespace with multiple functions
You can also declare variables and more functions, as many as you like. All of which are “local” to that namespace (it sort of acts like a controller to that code). Just remember the syntax changes within namespaces because you are referencing an object literal so you need to add commas after each statement instead of semi-colons.;MYNAMESPACE = {
name: 'MYNAMESPACE',
myFunction1: function()
{
console.log('running MYNAMESPACE.myFunction...');
},
myFunction2: function()
{
console.log('running MYNAMESPACE.myFunction...');
}
}
console.log(MYNAMESPACE.name); //variable call
MYNAMESPACE.myFunction1(); //function call
MYNAMESPACE.myFunction1(); //function call
A namespaces inside a namespace
Now your thinking what about a namespace inside a namespace, sort of a sub-namespace. Yes, this is also possible you would just need to make sure your main namespace is declared beforehand, like this:;var MYNAMESPACE = {};
MYNAMESPACE.SUBNAME = {
myFunction: function()
{
console.log('running MYNAMESPACE.SUBNAME.myFunction...');
}
}
MYNAMESPACE.SUBNAME.myFunction(); //function call
A self encapsulated jQuery namespace structure
Ok, now suppose you wanted to use a self encapsulated jQuery function (also known as an “anonymous function“, or “self executing function”) to wrap around your namespace but you want to be able to reference your objects, functions and variables held within. Firstly, you would need to declare the namespace outside the enclosing function to make the object assessable from outside, like so:;var MYNAMESPACE = {};
If you don’t create the variable in the outer scope you will surely see the following error: ‘ReferenceError: MYNAMESPACE is not defined’.
This is the full structure of the code which has full encapsulation using namespacing and includes the dollar sign ($) for use with jQuery code only inside the enclosed jQuery function to prevent naming conflicts with other frameworks.
;var MYNAMESPACE = {};
;(function($) {
MYNAMESPACE.SUBNAME = {
myFunction: function()
{
console.log('running MYNAMESPACE.SUBNAME.myFunction...');
}
}
})(jQuery);
MYNAMESPACE.SUBNAME.myFunction(); //function call
Using the window scope alternative
Passing through parameters to anonymous functions, like jQuery – is awesome because in your case its lets you use $ even if jQuery.noConflict() is set. So in that sense it would make perfect sense if your code in your namespace used ‘$’. You could actually still stick all the code inside the self executing function by just assigning MYNAMESPACE to the window scope (same effect as using var in the global scope above). Then you have your encapsulation and you’re free to use $.;(function($) {
// declare var in global scope
window.MYNAMESPACE = {};
MYNAMESPACE.SUBNAME = {
myFunction: function()
{
console.log('running MYNAMESPACE.SUBNAME.myFunction...');
}
}
})(jQuery);
MYNAMESPACE.SUBNAME.myFunction(); //function call
That’s it! I hope you learnt something about namespacing in JavaScript/jQuery. If not, please feel free to leave a comment. Next post, i’ll look into event namespacing, which is awesome.
Frequently Asked Questions (FAQs) about jQuery Function Namespacing
What is the purpose of namespacing in jQuery?
Namespacing in jQuery is a technique used to avoid collisions with other identifiers in the global scope. It’s a way to group functions, variables, and other data under a unique name. This is particularly useful in large projects where the risk of overwriting or misusing a variable is high. By using namespaces, you can ensure that your functions and variables don’t interfere with those in other scripts.
How do I create a namespace in jQuery?
Creating a namespace in jQuery is quite straightforward. You can create a namespace by defining an object and adding properties to it. These properties can be variables, functions, or even other objects. Here’s a simple example:var myNamespace = {
myFunction: function() {
// code here
},
myVariable: 'some value'
};
In this example, myFunction
and myVariable
are both part of the myNamespace
namespace.
Can I use namespaces with jQuery events?
Yes, jQuery provides a built-in mechanism for adding namespaces to events. This can be very useful when you want to unbind or trigger some events, but not others. For example, you might have multiple click events attached to a button, but you only want to unbind one of them. By using namespaces, you can do this easily.
How do I use namespaces with jQuery events?
To use namespaces with jQuery events, you simply add a period (.) followed by the namespace name when you bind the event. For example:$('#myButton').on('click.myNamespace', function() {
// code here
});
In this example, the click event has been namespaced with myNamespace
. You can then unbind or trigger this event separately from other click events on the same element.
What is the difference between a namespace and a module in JavaScript?
While both namespaces and modules are used to avoid naming collisions in JavaScript, they are not the same thing. A namespace is a simple object that encapsulates functions, variables, and other objects. A module, on the other hand, is a piece of reusable code that can be exported and imported in other parts of your application. Modules have their own scope and can have dependencies on other modules.
Can I use namespaces in TypeScript?
Yes, TypeScript supports namespaces as a way to organize code and prevent naming collisions. However, with the introduction of modules in ES6, the use of namespaces has become less common in TypeScript. Modules provide a more powerful and flexible way to organize code, and they are generally recommended over namespaces for new projects.
How do I create a namespace in TypeScript?
Creating a namespace in TypeScript is similar to creating one in JavaScript. You use the namespace
keyword followed by the name of the namespace. Here’s an example:namespace MyNamespace {
export function myFunction() {
// code here
}
}
In this example, myFunction
is part of the MyNamespace
namespace.
What is the best practice for using namespaces in JavaScript?
While namespaces can be useful in certain situations, they are not always the best solution. In modern JavaScript development, modules are often a better choice for organizing code. Modules have their own scope, which helps to prevent naming collisions, and they can be easily imported and exported in different parts of your application.
Can I nest namespaces in JavaScript?
Yes, you can nest namespaces in JavaScript. This can be useful for further organizing your code. However, keep in mind that each level of nesting adds to the complexity of your code, so it’s best to keep your namespaces as flat as possible.
How do I access a function or variable in a namespace?
To access a function or variable in a namespace, you simply use the namespace name followed by a dot and the name of the function or variable. For example, if you have a function named myFunction
in a namespace named myNamespace
, you would access it like this: myNamespace.myFunction()
.
Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.