CoffeeScript variation confusion

I am trying to understand how CoffeeScript variables change. According to the documentation:

This behavior is really identical to the Ruby scope for local variables.

However, I found that it works differently.

In CoffeeScript

a = 1 changeValue = -> a = 3 changeValue() console.log "a: #{a}" #This displays 3 

In Ruby

 a = 1 def f a = 3 end puts a #This displays 1 

Can someone explain this please?

+6
source share
2 answers

Local Ruby variables (starting with [a-z_]) are indeed local to the block they are declared in . So the Ruby behavior you posted is normal.

In your coffee example, you have a closure that refers to a. This is not a function declaration.

In your Ruby example, you have no closure other than a function declaration. This is different. The ruby ​​equivalent of your coffee:

 a = 1 changeValue = lambda do a = 3 end changeValue() 

In closure, the local variables present when the block is declared are still available when the block is executed. This is (one of) degrees of closure!

+8
source

The variable a used inside the changeValue function is the global variable a . This CoffeeScript will be compiled into the following JavaScript:

 var a, changeValue; a = 1; changeValue = function() { return a = 3; }; changeValue(); console.log("a: " + a); 

To prevent changeValue from changing the variable a (i.e., use a local variable), you need to either have a function argument named a (which would create this function as a local variable) or declare a as a local variable inside the function using var a = 3; (not sure what CoffeeScript is for this, I'm not a CoffeeScript guy).

Some examples of the scope of JavaScript variables.

0
source

Source: https://habr.com/ru/post/911637/


All Articles