Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is the JavaScript functional way to doing things. It's called closure: functions carry variable pointers from their current scope and from any other parent scope. So it's not only good practice, but this is the pattern you should normally follow instead of pushing around parameter objects, etc.</p> <p>Please notice that the "this" reference is special, it is never closured (as opposed to any other references) and thus always point the global object in anonymous functions.</p> <p>In fact a developer needs some time to fully employ the power of the closure feature - this is a basic example you just written. In more advanced (and not solely async) scenarios closure helps you to create "fire and forget" behavior, or can provide you with "private" variables that are not accessible from client code (useful for library development). Closure also help you isolate your code so that it will not mess with the global scope.</p> <p>1) Example: how to create protected variables with closures. You are able to acccess two methods that can access "protectedVariable" but you are not able to access it yourself - so the control is guaranteed.</p> <pre><code>function protectedScope(initData) { var protectedVariable = initData; return { getter: function() { return protectedVariable; } setter: function(v) { protectedVariable = v; } } } var methods = protectedScope(10); console.log(methods.getter()); </code></pre> <p>2) isolation: the following code will not garbage the global scope even with "global" function definitions</p> <pre><code>var API = (function() { var protectedVariable = 0; var myNotGlobalFunction() { return protectedVariable; } return myNotGlobalFunction; })(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload