|
The concern is that because Coffeescript automatically scopes variables to the scope of their first reference, it can introduce maintenance issues. Consider the following: foo = ->
bar = "woot!"
console.log bar
This compiles to: var foo;
foo = function() {
var bar;
bar = "woot!";
return console.log(bar);
};
bar is locally scoped to foo(). Now, 2 weeks later and 200 lines earlier, you come along and define: bar = ->
alert "Holy crap cheese is awesome!"
Which compiles to: var bar, foo;
bar = function() {
return alert("Holy crap cheese is awesome!");
};
foo = function() {
bar = "woot!";
return console.log(bar);
};
Now, all of a sudden, the "bar" reference in foo isn't scoped to foo() anymore, it's scoped globally, and once you invoke foo(), it'll replace the function bar with a string, potentially breaking your app. It's an ease-of-maintenance issue.This isn't consistent behavior, though. If you define your top-level bar() function after foo, like so: foo = ->
bar = "woot!"
console.log bar
bar = ->
alert "Holy crap cheese is awesome!"
Then you get "correct" scoping (and the outer bar is shadowed): var bar, foo;
foo = function() {
var bar;
bar = "woot!";
return console.log(bar);
};
bar = function() {
return alert("Holy crap cheese is awesome!");
};
On one hand, it could be argued that this is a "name things better" problem, but on the other, I have to agree that it'd be nice to be able to explicitly scope things when needed. Given that the behaviors are divergent based on what order the variables appear in, I'd say it's confusing enough that a way to explicitly say "hey, I know what I'm doing, I want to shadow any outer variables and declare local scope here" would be useful. |