tangrui
tangrui

Reputation: 43

Can CoffeeScript Be Translated into This Piece of JavaScript?

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

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

For example the following:

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

Upvotes: 4

Views: 141

Answers (5)

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

CoffeeScript, by design, doesn't allow you to shadow a previously declared variable. Yet, there is one case where it still happens:

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

That will result in a 1. Because a is function parameter, it's local to the function scope.

BTW, you could rewrite this as

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

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

Upvotes: 2

Dogbert
Dogbert

Reputation: 222168

You can use backticks to execute normal 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);
};

Upvotes: 4

Mike Aski
Mike Aski

Reputation: 9236

What about the following code?

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

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

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

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

From the CoffeeScript docs (emphasis added):

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.

Is there a reason you need to shadow a and can't just use a different identifier?

Upvotes: 5

Nitzan Tomer
Nitzan Tomer

Reputation: 164137

Well, if you do this:

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

You get:

var abc;

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

So just don't use the same variable name in the 2nd method scope and you are all good to go.

Upvotes: 1

Related Questions