Javascript – Storing function in object – bad practice?

functionjavascriptobject

Is it considered bad coding-practice to store functions in an object instead of just defining them (and therefore globally)?

Consider:

1.

Foo = {
    bar: function() {
        alert("baz");
    }   
}

Foo.bar();

vs.

2.

function bar() {
    alert("baz");
}

bar();

Sure, it might be slightly less code for the second example, but when you start to get lots of functions – it will get messy.
I find it way, way, cleaner to, for example, use Game.update() instead of using updateGame(); or similar. When getting deeper, like Game.notify.admin(id) and so on, it gives you even prettier code.

Is there any downsides by storing a function in an object?

Best Solution

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.