3 ms·
"One of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside a
by latortuga 17y ago
"One of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside another function is global..."
One sentence explaining that JS doesn't have variable scope proceeded by a sentence explaining that it actually does have scope? JS absolutely does have scoping rules. The follow up to this sentence (the section labeled "Anonymous Functions And The Module Pattern") seems to be ignorant of the presence of prototypes (in a prototype-based language!) and uses a needlessly complex and confusing way of explaining how to expose functions. What's wrong with the prototype?
- ewjordan 17y agoRe: scope, I think the author was mainly complaining that Javascript's scoping rules tend to err on the side of global visibility, rather than following the typical approach of scoping variables as narrowly as possible. Certainly it has scoping rules, it's just that they're unusually global for a language with Algol style syntax, and that makes it a common gotcha for people coming to JS from other places. What's wrong with the prototype? Nothing too bad, I suppose. Making things private is a little bit cleaner when you use the anonymous function/module method. By default, none of the methods are visible unless you explicitly expose them, whereas with a normal Javascript object you end up jumping through hoops to make private class methods actually be private - those hoops pretty much match what you do with the module pattern anyways, so... More importantly, the "needlessly complex and confusing" way of exposing functions (I don't necessarily disagree that it departs from "write what you mean", but I don't know that it's either too complex or confusing, it's a pretty simple pattern and often results in shorter code than prototyping would, esp. with private functions and data) is used just about everywhere when you work with other people's Javascript libraries. So it's a good thing to be familiar with it, as you're going to be looking at it almost every time you open up the source for any modern JS library.
- latortuga 17y agoRegarding your (and my) last point, I mean confusing in the sense that if you are returning some object with (as in his example, differently named) references to internal functions, it only makes it more difficult to track down code later. Worse for the coder, worse for the maintainer, and unnecessary.