You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
I believe the following paragraph, which appears shortly after Exercise 8 in "Functions" is misleading.
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:
or:
You can effect a closure using function parameters (as in the example which follows this one in the book):
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:
The text was updated successfully, but these errors were encountered: