Closures (inner functions)

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

A closure is the local variables for a function – kept alive after the function has returned

In other words,

a closure is formed when an inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned.


At which point it still has access to the local variables, parameters and inner function declarations of its outer function.

Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

1) We get the reference of the returned inner function.
2) Pass in a parameter so its inner function can grab onto it.
3) Execute the reference, which creates scope and grabs.

output:
Boooom! param is: 88

Now we do the same thing, but in a loop.

output:
Boooom! param is: 0
Boooom! param is: 1
Boooom! param is: 2

In an async situation, let’s say we have setTimeout that asks for a function to execute when a certain number of seconds have passed.

If we pass a function with a parameter (like what we have above), we’ll be able to have a closure and save state as well. We pass in one variable to the parameter, and the closure references that 1 parameter.

But because we do this in a callback, we must combine the 3 steps together.

So

1) We get the reference of the returned inner function.
2) Pass in a parameter so its inner function can grab onto it.
3) Execute the reference, which creates scope and grabs.

becomes an Immediately Invoked Function Expression:

therefore,

First it logs the callback function because we immediately execute it:
‘setTimeout: 88 √’

Then it returns the inner function. Due to the execution of the callback function, the inner function will create scope and reference parameter index from its local.

output:
After 2 seconds!…..inner func logs: 88

Async situation, in a loop:

We run an async operation where it executes a function after a second.
The inner function references it parameter, which is passed in via an Immediately Invoked Function Expression.

Under the hood, a closure is a stack-frame (which contains accessible variables), which has not been deallocated when the function returns. (as if a ‘stack-frame’ were malloc’ed instead of being on the stack!)

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

What is a Closure?

A closure is the combination of a function 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.

First, a simple Object with public and private properties

output:
blademaster.name – BladeMaster

Adding public function, and a Closure

To declare a closure, simply define a function inside another function. This is also called an inner function. Inner functions, are private scope by default. You can make it public for instances by assign public properties to it. In other words, you expose the function to be used.

If you assign a property to a function, you make it public and the instance can call it.
However, if its just the function, then it is used as private function for your class to use.

output:

Constructing Orc: BladeMaster
hands
This is an inner function

Using property variable in closure

After you define the closure, you can simply use the property name as is. i.e property ‘name’ in closure ‘growls’.

Using this.name in the closure vs this.name in the object

Closure has access to

  • its own scope
  • parent function’s scope
  • parent function’s parameters
  • DO NOT HAVE ACCESS to parent scope’s this because ‘this’ is inside of a function (either stand-alone or within another method) will always refer to the window/global object.


output:
Constructing Orc: BladeMaster
Toro: For the burning blade!
Toro
local
hands
BladeMaster
ERROR this is undefined

Public properties assigned to Inner Functions can access “this”

Notice that when we assign public properties on Inner Functions, we can access this.
However, a standard inner function (no public properties assigned to it) will not be able to have access to the parent scope’s this.


output:
The Masters
who’s playing in it!?
[ { name: ‘T. Woods’, age: 37 },
{ name: ‘P. Mickelson’, age: 43 } ]
1) own vars
123
hehe
2) outer function’s vars
888
outer limits
3) outer function’s parameter
merry xmas!
4) Inside closure: undefined
1) own vars
123
hehe
2) outer function’s vars
888
outer limits
3) outer function’s parameter
merry xmas!
4) Inside closure: [global object]

If we do want private inner function to access parent scope

see http://chineseruleof8.com/code/index.php/2018/02/07/arrow-functions-js/ for detailed explanation
of using 3 ways to how to use ‘this’ in inner functions:

Using parent scope variable
Using bind or call
Using arrow

More Example

First, we create the Person object. In the constructor declaration, we have a private property called pvtArray.
Any functions within our class Person can access it as a outer scope, global variable.

We have a public property called nickname. This property is accessed with this within our class Person.

However, there is a caveat.

Let’s say we declare a public function called displayInfo. It is considered a 1st layer function and can see the ‘this’ object.

Any functions within function displayInfo are considered (2nd and later) functions. These functions cannot see the ‘this’ object and any reference to this will result in undefined.

Thus, in Person, if you are to see the commented out setTimeout function, this.nickname will be undefined because ‘this’ references Timeout’s this. In Timeout, there is no property nickname.

As mentioned earlier, we can use any of the 3 ways to bind ‘this’ to the correct context: fat arrow, local stack ‘self’, or bind.

Now we are going to write a Boss class. This Boss class has a public function called peekOnRandomEmployee.

We declare a new Person in that function. Then directly call displayInfo on it.

displayInfo needs a anonymous function as a parameter for its callback. We declare a anonymous function and pass it in.
The point here is that our anonymous function is a 2nd and later level function. Thus, its ‘this’ reference is on Timeout.

If we are to use the fat arrow function, the ‘this’ will then be assigned to its parent context. Its parent context is the instance. Hence, our ‘this’ inside the callback will be assigned to the instance.

Boss example

Notice how it references outer function variables a and p. By definition, a function’s scope extends to all variables
and parameters declared by its surrounding parents. And of course any global variables as dictated by scope rules.