So I\'ve been reading through Javascript - The Good Parts and one thing that Crockford points out is the use weakness of global variables in Javascript, in such a way that if yo
Making it a global function is not the answer. Why wouldn't you do this? This keeps x out of the global namespace.
(function () {
var x = 'meh';
alert(typeof x); //string
})();
To create applications with javascript, you must attempt to keep variables in a local scope, and anything inside a namespace. It's a good pratice and prevent a serie of harm codes and unespected behaviors.
read this
it's a article talking about the vantages of doing that.
That's a perfectly legal way of doing things -- the variables inside of your function (as long as they are prefaced by var
) are local to the function. It's called the module pattern, and it's very well accepted.
(function (global) {
global.x = 'meh';
})(window);
(function () {
alert(typeof x); // string
})();