Can CoffeeScript be translated into this part of JavaScript?

function abc() { var a = 1; var func = function() { var a = 2; } func(); alert(a); } 

Pay attention to var , in a piece of code the result of a will be 1, but if var omitted, the result will be 2, but I found that Coffee could not translate to this.

For example, the following:

 abc = -> a = 1 func = -> a = 2 return func() alert(a) return 
+4
source share
5 answers

CoffeeScript, by design, does not allow you to obscure a previously declared variable. However, there is one case where this is still happening:

 abc = -> a = 1 func = (a) -> a = 2 return func() alert(a) return 

This will result in 1 . Since a is a function parameter, it is local to the scope.

By the way, you can rewrite this as

 abc = -> a = 1 do (a) -> a = 2 alert a return 

where do (a) -> a = 2 equivalent to ((a) -> a = 2)() .

+2
source

From CoffeeScript Docs (highlighted by me):

Since you do not have direct access to the var keyword, it is not possible to specifically create the shadow of an external variable , you can only refer to it.

Is there a reason you need to obscure a and cannot just use a different identifier?

+5
source

You can use backticks to execute regular js.

 abc = -> a = 1 func = -> `var a = 2` return func() alert(a) return 

Compiled form

 var abc; abc = function() { var a, func; a = 1; func = function() { var a = 2; }; func(); alert(a); }; 
+4
source

Well, if you do this:

 abc = -> a = 1 func = -> b = 2 alert(b) return func() alert(a) return 

You are getting:

 var abc; abc = function() { var a, func; a = 1; func = function() { var b; b = 2; alert(b); }; func(); alert(a); }; 

Therefore, just do not use the same variable name in the 2nd area of ​​the method, and you are fine.

+1
source

What about the following code?

 abc = -> a = 1 func = -> @a = 2 return func() alert(a) return 

I agree: this is not exactly the same code, but it behaves as expected ...

Is your question just a stylistic composition or do you have a "real world" problem?

0
source

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


All Articles