Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Namespacing

I wish to make my javascript more more modular by splitting it up into different files and giving each file a 'sub' namespace like so.

subA.js

if(typeof ex == "undefined") {
    var ex = {};
}

ex.subA = function() {
//all functions of subA here
}

And same for subB etc.

At the moment I have 1 file, ex.js

var ex = (function() {
    //private vars/funcs
    return {
        //public vars/funcs
    }
})();

It looks like I should move most of my functions to subA.js and subB.js but still include ex.js at the start, with subA.js and subB.js afterwards.

I have a number of questions.

  1. I'm having a hard time remembering how I made the initial namespacing file, ex.js. It looks like the anonymous function is there to make everything private initially, but I can't remember why it needs to be enclosed in parentheses and then executed straight away with the (); at the end.

  2. Following on from q1, should my sub files be in the same format as ex.js, ie, have the anon function wrapped in parentheses and executed straight away?

  3. It looks like the sub files will only have access to the public functions of ex, is this true? If it is, how can I allow my sub files access to the private functions as well?

  4. In my HTML file, in my document.ready function (jQuery), should I be initialising ex to a variable or can I call each function individually by going

$(document).ready(function() {
    ex.doSomething();
    ex.doSomethingElse();
}

Is there a difference between the two? I think that when ex.js is included, a global variable ex is created straight away (due to the anonymous function being executed straight away), so I shouldn't need to redefine it in document.ready.

  1. Is the first if statement in subA.js any different from var ex = ex || {}; Which is better?

  2. What js code style standards do you use?

If you read through all this you already deserve an upvote, cheers.

like image 979
Michael Avatar asked Oct 07 '11 07:10

Michael


People also ask

What is Namespacing in JavaScript?

JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

Does JavaScript support namespace?

JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.

What is JavaScript namespace pollution?

Polluting Global namespace causes name collision. This name collision is very common in large projects where we may be using several javascript libraries. Let's discuss in detail what a name collision is. let's take a scenario in which 2 teams named A1 and A2 are working on a project.


1 Answers

1. The function(){ return{}} is a closure to add "privacy" to the variables and functions you don't want to be accessible anywhere else but within the scope of that function. The parentheses around the function (function(){}) create a function expression. They are used, because the parser will complain when you try to execute a function immediately function(){}() without passing any argument to ().

2. If you want subA or any other extending object to have its own subfunctions, then yes, you have to declare it like that, but not neccesarly a clousure though.

You can do

ex.subA = function(x, y){
    return x+y;
}

which can be called var sum = ex.subA(2, 3);

Or you can do

ex.subA = (function(){

    return {
        add: function(x, y){
            return x+y;
        },
        multiply: function(x, y){
            return x*y;
        }
    }
})();

Then call it var sum = ex.subA.add(2, 3); var multiplication = ex.subA.multiply(2,3);

There are many ways to do this.

3. Yes, it is true. You can make the private functions public. The closure won't allow any other way to do it.

4. If you would like to alias, yes you can assign it to a variable. However, there is no need to. It will work fine the way you are describing it.

Read Essential JavaScript Namespacing Patterns to understand some fundamentals and patterns in javascript namespacing.


Is the first if statement in subA.js any different from var ex = ex || {}; Which is better?

First of, the if statement should be if(typeof ex == 'undefined'), the typeof returns a string. There isn't any need to check if ex is false.

Yes, it is different. The if statement will not do any variable assignment if the variable ex is already defined. Therefore, the if statement is better.

What js code style standards do you use?

Depends on the scope of the project, but mostly deep object extending with a helper function.

like image 116
Shef Avatar answered Oct 14 '22 22:10

Shef