JSFiddle - React, Tailwind, and code Playground

E.Elliott- Closures

by nickadeemus2002

HTML

<script src="https://cdn.rawgit.com/zloirock/core-js/master/client/shim.min.js"></script>
<script src="https://wzrd.in/standalone/tape@latest"></script>
  <script src="https://wzrd.in/standalone/tap-browser-color@latest"></script>
<script src="//fb.me/react-with-addons-0.14.3.js"></script>
<script src="//fb.me/react-dom-0.14.3.js"></script>
  <script>
    window.test = tape;
    tapBrowserColor();
  </script>

JavaScript

/*
What is a Closure?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.
The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
*/



/*
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods. 
*/
const getSecret = (secret) => {
  return {
    get: () => secret
  };
};

test('Closure for object privacy.', 
			assert => {
  			const msg = '.get() should have access to the closure.';
  			const expected = 1;
  			const obj = getSecret(1);
  			const actual = obj.get();

  			try {
    			assert.ok(secret, 'This throws an error.');
  			} catch (e) {
    			assert.ok(true, `The secret var is only available
      		to privileged methods.`);
  			}

  			assert.equal(actual, expected, msg);
  			assert.end();
});

/*
n the example above, the `.get()` method is defined inside the scope of `getSecret()`, which gives it access to any variables from `getSecret()`, and makes it a privileged method. In this case, the parameter, `secret`.
Objects are not the only way to produce data privacy. Closures can also be used to create stateful functions whose return values may be influenced by their internal state.
*/


// Secret - creates closures with secret...