Friday, November 29, 2019

JavaScript Closures

Variable scope:

  • scoping is how you search for a variable
  • the scope of a variable is the area where that variable can be accessed by name

JavaScript language has lexical scope also known as static scope:

  • JavaScript do variable lookup in the scope in effect when a function is defined: the textual arrangement of its definition
  • functions are executed in the variable scope in effect when they were defined

Nested function closures

function getCounter() {
  let counter = 0;
  return  function() {
    return ++counter;
  };
}
var count = getCounter();
// local variable counter still exist
count(); // 1
count(); // 2
  • Invoke the getCounter function, this invocation creates the local variable counter and set the variable with 0. Then, the getCounter returned; when the nested function is invoked, out of its outer function, it remembers the variable of the outer function. That's weird, counter is a local variable of getCounter, as soon as getCounter exits, local variables are gone.

How nested function works in JavaScript?

  • the nested function's scope chain in effect when the function is defined is still in effect when the function is invoked out of the outer function
  • functions are called closures because they capture local variables. Functions keeps a reference to local variables, they do not make a copy of like in Java

Example 1: lexical scope for a closure

See the Pen Closure's lexical scope by Massimiliano De Simone (@maxdesimone) on CodePen.

What's the use of closures?

  • You can use a closure to associate some data with a function that operates on that data, anywhere you may use an object with some properties and a method operating on those properties.
  • Closures allow you to create private members: there no way to make object's properties private in JavaScript. With closures, variables in the function scope become private members of the function, because they can only be accessed by the closure.

Example 2: closure with a parameter

See the Pen closure with a parameter by Massimiliano De Simone (@maxdesimone) on CodePen.

Example 3: more closures sharing data

You can have two or more nested functions to be defined within the same outer function and share the same scope chain

See the Pen more closures sharing data by Massimiliano De Simone (@maxdesimone) on CodePen.

Module Pattern

  • to allow the user of your code to invoke only some functions, you return an interface object from the nested function;
    the interface object contains only the functions you want to be invoked
  • the process of wrapping code in a function from where you then return an interface object is called the module pattern.

No comments:

Post a Comment