Smooth CoffeeScript

Page 52

Functions

inside the function. If a function calls another function, the newly called function does not see the variables inside the first function. andHere = -> try show aLocal catch e then show e.message isHere = -> aLocal = 'aLocal is defined' andHere() isHere()

# Not defined

However, and this is a subtle but extremely useful phenomenon, when a function is defined inside another function, its local environment will be based on the local environment that surrounds it. isHere = -> andHere = -> try show aLocal catch e then show e.message aLocal = 'aLocal is defined' andHere() isHere()

# Is defined

◦•◦ Here is a special case that might surprise you: varWhich = 'top-level' parentFunction = -> varWhich = 'local' childFunction = -> show varWhich childFunction child = parentFunction() child() 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.

◦•◦

51


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.