r/programming • • Dec 22 '11

The Problem with Implicit Scoping in CoffeeScript

http://lucumr.pocoo.org/2011/12/22/implicit-scoping-in-coffeescript/
83 Upvotes

116 comments sorted by

View all comments

Show parent comment

1

u/ctrldavid Dec 23 '11 edited Dec 23 '11

One possibility would be to have a 'strict' variant of the function syntax, where you explicitly list the variables you wish to close over. I believe c++11 does something similar.

a = b = c = 1
# Normal function, like current implementation
f = ()->
  a = b = c = 2

f() # a == b == c == 2

# 'Strict' function. Explicitly lists variables closed over
f = [a,b]() ->
  a = b = c = 3

f() # a == b == 3, but c still equals 2 from before.

which would compile to something like:

var a, b, c, f;

a = b = c = 1;

f = function() {
  return a = b = c = 2;
};

f();

f = function() {
  var c;
  return a = b = c = 3;
};

f();