8

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 your product is expanded in some manner, and it relies on a 'global' variable it could be inadvertently set.

That's all good and fine and I understand the pros/cons of protecting variables, in other manners such as closures as well. However, I was doing some thinking, and wrapping code in a function like so:

(function () {
    var x = 'meh';
})();
(function () {
    alert(typeof x); // undefined
})();

gives it variable scope, which thereby prevents cross contamination of variables. I'm not sure if there's a blatant downside to this approach though and wondered if the community had any input, or if I'm just overthinking things and ignoring the main point.

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome. Appreciate the link. I wonder why this isn't really mentioned in his book (so far, it's possible it is later, but it'd make sense to have it in the part bashing global variables). At least I know I'm not being overly analytical for once.
This is my nit-picking day, apparently, but those things are not called closures in a strict sense (in a general computer science sense, all JavaScript functions are closures): those self-invoking anonymous functions would only be closures if they are used outside of the scope in which they were defined (e.g., when attaching an anonymous function to an event listener within a function that exits before the listener is detached).
@Marcel -- thanks, I've updated it to use function rather than closure.
0

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.

Comments

0

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
})();

1 Comment

The point in the example was to get undefined, therefore isolation from eachother.
0
(function (global) {
    global.x = 'meh';
})(window);
(function () {
    alert(typeof x); // string
})();

1 Comment

Please try to avoid code only answers and add some detail or explanation. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.