Defining JavaScript Functions with Namespace

2016-11-17 JavaScript

I was working on a small jQuery plugin, where I wanted to define a common jQuery function to be used multiple times as per requirement. This may be a nested function declarion at some point.

Example: Nested JavaScript Function

// function 1
function x(){
    alert('function x fired');

// function 2
function y(){
    alert('function y fired');

// calling

Above code run x() first and then y(). function y() has a call of another function x() therefore it will be firing up alert('function y fired') first and then alert('function x fired').

Now let’s come to the main part! Below is a way to define functions more better way - using NAMESPACE.

Example: Nested JavaScript Function using Namespace methodology

(function($) {
    var namespace;
    namespace = {
        something : function() {
            alert('hello there!');
        bodyInfo : function() {
    window.ns = namespace;

$(function() {

Snippet Credit

Further Reading

  1. Namespacing in JavaScript
  2. Strict Mode Is Coming To Town
comments powered by Disqus