As of now, I’ve been using self-executing anonymous functions in order to avoid having variable naming issues:
(function () {
var a, b, c;
a = 5;
b = 10;
c = 15;
console.log('No problema!');
]());
I also know that using the onload function is also an alternative approach:
window.onload = function () {
var a;
a = 25;
console.log('Yay!!!');
}
But I really dislike how my code is completely trapped inside a function – is there an approach that I could take with JavaScript objects that could help me avoid using self-executing functions?
On most of today’s browsers, functions simply are the unit of encapsulation. If you want to create a scope for a variable, you make it local to a function.
But today with many server side JavaScript installations, modules exist, many based on require.js. If you write apps with Nodejs, you’ll be familiar with it already.
The next version of JavaScript is coming soon, though. Named ES6, ES.next, Harmony, or JavaScript.next, this new JavaScript will have modules for your information hiding, as well as block scope. Many browsers are starting to implement features of the language now. You can experiment with in at http://repl.it, among other places. You can use Google’s Traceur compiler to compile a language including many of the ES6 proposals into today’s JavaScript.
TL;DR: for now: stick with functions in the browser. Or use require.js for your server side applications. Hang on because ES6 is coming.