Given the following code:
outer=1
f=->
local=1
outer=0
local+outer
coffeescript creates a var
for local
but re-ueses outer
:
var f, outer;
outer = 1;
f = function() {
var local;
local = 1;
outer = 0;
return local + outer;
};
Which is what your expect.
However, if you use a local variable in a function it depends on the outer scope if the variable is declared local or not. I know this is a feature, but it was causing some bugs, because I have to check all outer scopes for variables with the same name (which are declared before my function). I wonder if there is a way to prevent this type of bug by declaring variables local?
Right-click an existing front panel object or block diagram terminal and select Create»Local Variable from the shortcut menu to create a local variable. A local variable icon for the object appears on the block diagram. You also can select a local variable from the Functions palette and place it on the block diagram.
In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.
The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below.
This kind of error usually comes up when you aren't using appropriately descriptive variable names. That said, there is a way to shadow an outer variable, despite what the accepted answer says:
outer=1
f=->
do (outer) ->
local=1
outer=0
local+outer
This creates an IIFE, with outer
as it's one argument. Function arguments shadow outer variables just like the var
keyword, so this will have the behavior you expect. However, like I said, you should really just name your variables more descriptively.
No, that feature is explicitly not available in CoffeeScript (emphasis mine):
This behavior is effectively identical to Ruby's scope for local variables. Because you don't have direct access to the
var
keyword, it's impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that you're not reusing the name of an external variable accidentally, if you're writing a deeply nested function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With