Javascript - Storing function in object - bad practice? [closed]

Solution 1:

The first approach is preferred. This way you are explicitly defining the scope of your functions instead of polluting the global scope. There are no downsides of using the first approach. Only upsides :-)

Conclusion: always use the first approach to define functions. The second is like javascript in the 90s, let's leave it rest in peace back in the past and use proper scoping.

Solution 2:

In this specific case go with the first one. But if you Foo object gets really complex you might want to use another approach that will give you the opportunity to use a constructor. And also the first approach sometimes is not the best when it comes to the function's scope:

function Foo(appName){
    this.name = appName;      
}

Foo.prototype.Bar = function(){
   alert(this.name)
}

var a = new Foo("baz");
a.Bar();

Solution 3:

There is no magic with namespace objects, nor will you necessarily have any issues if you use lots of global variables. The main reason to use "namespace" objects is to reduce the potential for duplicate global variable names. A second reason is to group similar functions together for convenience, e.g:

// Object example (suggested best practice):
// DOM functions are under myLib.dom
myLib.dom.someDOMFunction0;
myLib.dom.someDOMFunction1;

// Utility functions are under myLib.util
myLib.util.someUtilityFunction0;
myLib.util.someUtilityFunction1;

Note that the above has practically the same chance of duplicates as similarly global variables:

// Global variable example:
myLib_dom_someDOMFunction0;
myLib_dom_someDOMFunction1;

myLib_util_someUtilityFunction0;
myLib_util_someUtilityFunction1;

Of course the former is generally preferred because it seen as easier to work with. I'm not advocating that you adopt the second approach (I use the first), just pointing out that while there is an issue with creating lots of global variables, so–called "global namespace pollution" is greatly overrated as a hazard.