Skip to content

Scoping/closure example incorrect #23

@altaurog

Description

@altaurog

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions