0

I am currently writing all javascript functionality of a certain page in JQuery's document.ready handler:

$(document).ready(function() {
    var one, two, three;
    function f1(par1) {}
    function f2() {}
        ...
});

I feel that this isn't optimal or according to Javascript best practices. What I need is a private scope for the page's functionality, nothing needs to be called externally.

I've seen a number of different ways:

jQuery source

(function(window) { 
    var anObj = {};
    ... 
    window.functionality = anObj;
}(window));

A function that is self-invoked with the window as parameter, then setting the functionality object of your application on it.

Codemirror source

window.functionality = (function() {
   var functionality = {};
   ...
   return functionality;
}());

Very similar to what jQuery does, but setting the functionality object indirectly on window by making a self-invoking function return something first.

This question

var functionality = {};
(function(obj) { obj.f1 = ... }(functionality));

Creating a local variable (instead of on window), and setting its content inside a self-invoked function (why?)

How do I declare a namespace in JavaScript?

var functionality = { 
    f1: function(){}, 
    f2: function(){}
}

Pretty much the same as the previous thing but setting the contents without a self-invoking function (again why use or not use the self invoking function?).

So... which way is best?

Community
  • 1
  • 1
MarioDS
  • 12,895
  • 15
  • 65
  • 121
  • With private functionality, do you mean functionality that is only run/seen on a specific page? – T. Junghans May 17 '13 at 07:49
  • @TJ yes, it is the javascript that controls the page during its lifetime, but should not be reachable by other javascript also on the page. – MarioDS May 17 '13 at 07:50

1 Answers1

2

I would suggest the module pattern for this, where a page is treated as a module. There is a lot of information about the javascript module pattern on the web. Have a look at http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html.

I've used an example from the link and modified it a bit:

var MyApp = MyApp || {};
MyApp.PageX = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

What is happening here, is that a set of properties and methods is defined and namespaced to MyApp.PageX, MyApp being the global. So this will work:

MyApp.PageX.moduleProperty; // 1
MyApp.PageX.moduleMethod();
T. Junghans
  • 11,385
  • 7
  • 52
  • 75