Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scoping/closure example incorrect #23

Open
altaurog opened this issue Oct 18, 2012 · 0 comments
Open

Scoping/closure example incorrect #23

altaurog opened this issue Oct 18, 2012 · 0 comments

Comments

@altaurog
Copy link

I believe the following paragraph, which appears shortly after Exercise 8 in "Functions" is misleading.

Here is a special case that might surprise you:

varWhich = 'top-level'
parentFunction = ->
  varWhich = 'local'
  childFunction = ->
    show varWhich
  childFunction
child = parentFunction()
child()

→ local

parentFunction returns its internal function, and the code at the bottom calls this function. Even though parentFunction has finished executing at this point, the local environment where variable has the value 'local' still exists, and childFunction still uses it. This phenomenon is called closure.

If I understand correctly, this has nothing to do with closures. Both the reference to varWhich in parentFunction and that in childFunction access (and modify) the global var directly. Modifications made thereto are not limited to the local scope, since there is no varWhich in local scope:

varWhich = 'top-level'
aFunction = ->
  varWhich = 'local'
bFunction = ->
  show varWhich
aFunction()
bFunction()

→ local

or:

varWhich = 'top-level'
parentFunction = ->
  varWhich = 'local'
  childFunction = ->
    show varWhich
  childFunction
child = parentFunction()
varWhich = 'not a closure'
child()

→ not a closure

You can effect a closure using function parameters (as in the example which follows this one in the book):

varWhich = 'top-level'
parentFunction = ->
  varWhich = 'local'
  childFunction = (myVar) ->
    -> show myVar
  childFunction(varWhich)
child = parentFunction()
varWhich = 'not a closure'
child()

→ local

You could even give childFunction a parameter of the same name, although it's not a very good idea to do that in coffeescript. IMO given coffeescript's scoping rules, the compiler shouldn't allow this:

varWhich = 'top-level'
parentFunction = ->
  varWhich = 'local'
  childFunction = (varWhich) ->
    -> show varWhich
  childFunction(varWhich)
child = parentFunction()
varWhich = 'not a closure'
child()

→ local
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant