Hacker News new | ask | show | jobs
by locci 5287 days ago
I think this is a recurring discussion from the dawn of coffeescript. See for example: https://github.com/jashkenas/coffee-script/issues/238

I really don't understand why this isn't being fixed: doesn't global by default break encapsulation? I'm probably missing something, but this is the main reason I haven't tried coffeescript yet.

1 comments

Just to be completely clear, variables are only at top level scope if you declare them at top-level scope. The variables "x" below are completely encapsulated within f1 and f2. The variables at top-level scope are intentional in the code below--I really do intend f1, f2, and how_many_times_functions_have_been_called to refer to the same entity throughout the file.

  how_many_times_functions_have_been_called = 0

  f1 = ->
    how_many_times_functions_have_been_called += 1 # refers to top-level scope
    console.log x # undefined
    x = 1
    console.log x # 1

  f2 = ->
    f1() # refers to f1 at top-level scope
    how_many_times_functions_have_been_called += 1 # refers to lop-level scope
    console.log x # undefined
    x = 2
    console.log x # 2

  f1() # you can call f1, it's at top-level scope
  f2() # you can call f2, it's at top-level scope
  console.log how_many_times_functions_have_been_called # 3, refers to top-level scope
  console.log x? # false, x does not exist at top_level scope
Yes, I probably wasn't very clear: what I meant is that a programmer writing a function somewhere in a program must have a complete knowledge of the scope where the function is and will be in the future, including changes in global variables exposed by the interpreter/browser. In the end I would find me forced to add a prefix to all the variables in order to avoid collisions, just like I would be forced to do, if the language only had a single global scope.

This behaviour seems quite unreasonable to me, but I haven't been able to find explanations about it, other than it's expected behaviour.

Fortunately, what you're describing isn't how it works.

CoffeeScript will automatically declare all variables in the nearest lexical scope it can find. The top-level scope in CoffeeScript isn't global -- it's the top of the file. You don't have to know anything about what values may or may not exist in global scope at any given moment ... all you have to know is what variables are visible in your function's enclosing scopes, just within the file you're working in.

Oh, I see. And you fiddle with globals by manipulating the window/exports object, which I assume are reserved identifiers.

Thanks a lot for clarifying that, it doesn't look that bad this way.