Category Archives: javascript

Function Constructor, Prototype, and mix

ref – http://a-developer-life.blogspot.com/2011/11/7-ways-to-create-objects-in-javascript.html

Creates a Person object, which has attribute name, and function getName.

The constructor pattern is compact, reusable and gives a classical OO syntax.

However, here’s the problem:

In our example the field getName is a function.

In Javascript functions are objects. Thus, 10 object will have 10 function. And this means we define ten extra objects.

Escalate this to a thousand and realize how much memory is being wasted!

It would be nice if all instances of Person share the same getName object, since this holds behavior and not data.

Prototype

Functions are very special in Javascript. They are objects, they can create other objects and they automatically get a field called prototype.

A prototype is a plain object with a single field, called constructor, pointing to the function itself.
What makes it special is that every object created through a function inherits the function’s prototype.

Thus, personOne and personTwo will both have attribute name initialized to “Diego”. Therefore, all instances share the same fields.

Function constructor gives you objects with the instantiation’s own functions, but numerous instances take up too much space because each function is like an object.

Prototype let’s you escape that by using the prototype property. This let’s the instantiations share attributes and functions.

The function/prototype combination let’s you take advantage of both approaches.

While sharing behavior (the getName function), each object has its own data and state in the attribute ‘name’.

attach functions to objects

First declare your objects

Then you declare a function…

You can literally attach functions to objects like so:

Where the function uses ‘this’ to access the calling object’s attributes.
Using them like this:

would give:

name is: gary, age is: 25
name is: ricky, age is: 35

Closures (js)

http://javascriptissexy.com/understand-javascript-closures-with-ease/
https://medium.freecodecamp.org/whats-a-javascript-closure-in-plain-english-please-6a1fc1d2ff1c
http://ryanmorr.com/understanding-scope-and-context-in-javascript/

Udemy Example

When I invoke function greet, I’m gunna get a reference to another function, in which I can invoke again.

at 1), greet was invoked, so it was pushed then popped from the execution stack.

at 2) when you invoked the returned function object, it still can access variable ‘whattosay’. How is this possible?

First we have the Global Execution Context.
When greet function was invoked, greet() Execution Context was pushed.

The variable that was passed to greet() is sitting in that Execution Context.

We all know that every execution context have memory space reserved for variables and what not. When the execution context gets popped, the memory space presumably also leaves. The JS engine would eventually garbage collect it. However, in our case, in the creation phase of greet()’s context, the variables ‘whattosay’ and the return anon function were stored in memory. The return anon function is a function definiton, and as with any function defintiions, it gets stored in memory.

We invoked sayHi, which is the anon function in memory.
sayHi() Execution Context is pushed onto the context stack.
It runs through the function and are able to use variable ‘whattosay’ because it’s referencing the object that’s existing in memory.

This phenomenon is called ‘the Execution Context has closed in on its outer variables’. It has captured them.

Closure in Memory

Let’s explain the same code, but we’re going to use async capabilities, instead of a returned function.
We start with the same code.

In the very beginning, we set up the basic. We invoke the global context.

Global (Creation Phase) – which sets up its this, outer references, greetings definition, all in memory

Global (Execution Phase) – During the execution phase, go line by line and execute each line. We first see the function definition greetings. Its already in memory so we skip it. We step and then invoke greetings function. When invoking the function it creates a context, which we push onto the context stack.

Greetings Context (Creation Phase) – we put variable name into memory and assign it to undefined. We set the ‘this’ reference to the global object, and reference to the outer environment

Greetings Context (Execution Phase) – Now comes the line by line execution. Variable name points to immutable literal string ‘ricky’.
Then it invokes setTimeout function. setTimeout function is an async function so it gets put in memory.

Since the setTimeout function was invoked, it needs to go through creation phase and execution phase.
In the creation phase, it sets up the ‘this’ and outer reference for setTimeout. Then it sees the function definition in the first parameter. It puts that anonymous function in memory.

1) For setTimeout’s execution phase, it starts on the “2 second wait”. Once it starts, we continue on to the next step, which is the end of greetings function.
2) The end of greetings function signals that we pop greetings context from the execution stack.

1) Finally, the two seconds are up.
2) setTimeout executes its callback. It invokes the anon function. Thus, it gets pushed onto the context stack.
3) setTmeout completes and thus, gets removed from memory.

then,

1) The invocation of the anon function goes through its Creation Phase. There’s literally nothing there except a log. However, we see that in the log, we are referencing name variable from the memory.
2) We print the log statement
3) the anon function now finishes is popped off the context stack.

In the end, only the global context is left. In memroy, since nothing else is using name, nor anon function in this context, they will be garbage collected.

What is a closure?

Closure is the act of capturing an object and separating it from its original scope, making it available to the capturing function forever.

First off, you create a closure whenever you define a function, NOT when you execute it.

In other words, a closure is formed when a nested function is defined inside of another function, allowing access to the outer functions variables.

For example,

returning the inner function allows you to maintain references to the local variables, arguments, and inner function declarations of its outer function

This encapsulation allows us to:
1) hide and preserve the execution context from outside scopes
2) while exposing a public interface and thus is subject to further manipulation.

setTimeout example

First Try…

We’re accessing the i from the outside scope’s for loop via parent scope.

The result is:

0
1
2
3
4
5
6
7
8
9

1 second later…

10
10
10
10
10
10

not really what we want…

2nd try

We wrap an IIFE around it so that we save the index variable. Now, for each setTimeout invocation at each index i,
we have successfully saved i into parameter index. Each Execution Context is pushed on with the index variable.

Then the setTimeout inside will be able to access the index variable.

for loop: 0
for loop: 1
for loop: 2
for loop: 3

AFTER 3 SECONDs…

callback: 0
callback: 1
callback: 2

One of the most popular types of closures is what is widely known as the module pattern; it allows you to emulate public, private, and privileged members:

Module Pattern

The module acts as if it were a singleton, executed as soon as the compiler interprets it, hence the opening and closing parenthesis at the end of the function. The only available members outside of the execution context of the closure are your public methods and properties located in the return object (Module.publicMethod for example). However, all private properties and methods will live throughout the life of the application as the execution context is preserved, meaning variables are subject to further interaction via the public methods.

or executed in the context of the window object:

The closure has three scope chains

– it has access to its own scope (local variables)
– it has access to the outer function’s variables (including parameters)
– and it has access to the global variables.

When you put a function in a variable like this, you are assigning the variable func, a reference to the function sayHello, NOT A COPY.
Via definition of a reference, anything you do on the func reference will be done on the original function.

For example, when we add a property to reference func:

our function sayHello will also have it because func is a reference to sayHello.

Lexical Scoping

Describes how a parser resolves variable names when functions are nested. The word “lexical” refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available.

Nested functions have access to variables declared in their outer scope.

init() creates a local variable called name and a function called displayName().
The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function.

The displayName() function has no local variables of its own.

However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

However, the same local variables in displayName() will be used if they exist.

Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function.

Scope is created when you execute a function

When you call a function like init() you create a scope during the execution of that function. Then that scope goes away.

When you call the function a second time, you create a new different scope during the second execution. Then this second goes away as well.

These two scopes that were created in the example above are different. The variable answer here is not shared between them at all.

Every function scope has a lifetime. They get created and they get discarded right away. The only exception to this fact is the global scope, which does not go away as long as the application is running.

Closures are created when you DEFINE a function

When you define a function, a closure gets created.

Unlike scopes, closures are created when you DEFINE a function, NOT when you execute it. Closures don’t go away after you execute that function.

local scope, parent scope, and global scope are all referenced by the closure. NOT COPIED:

Don’t confuse closures with scopes

In the simple example above, we have three functions and they all get defined and immediately invoked, so they all create scopes and closures.

The scope of function one() is its body. Its closure gives us access to both its scope and the global scope.

The scope of function two() is its body. Its closure gives us access to its scope plus the scope of function one()plus the global scope

And similarly, the closure of function three() gives us access to all scopes in the example. This is why we were able to access all variables in function three().

Another Example

If not global variable v…

Since closures have REFERENCE to variables in scope, they have read/write access

This is why we can change global variables everywhere. All closures give us both read/write access to all global variables.

Closures can share scopes

double and square both share scope parent. This means their closure references variables from parent. Specifically, variable a.
Hence, when we call double the first time, double references var a from parent. It does 10 + 10 = 20. Parent’s var a is now 20.

Then, square references var a from parent. a is now 20 from the call to double due to reference usage. square does 20 * 20 = 400.
Parent’s a is now 400.

We execute double again. double’s closure references a from parent which is 400. It does 400 + 400 = 800. Parent’s var a is now 800.

Another example


output:
3
2

Things can get weird though – People Example

Here we pass an array of objects into a function. We are expecting this function to update property id of our objects.

We use a loop to assign index to the array element’s id property.
The anonymous function created here is stored in heap memory, as well as the var i.

After we run this, the result id are all the same, 103.

Since var i, and all three anon functions are stored in heap memory, when we try to access the ids later in the future, the var i is already 103.
Thus, when you invoke those functions in the future, they will be access i that is 103.

Solution

We need to make sure we store the correct i somehow, and not an i that has already ran through its course to the end.

We do this through two ways:

  • Invoking the function and storing the value right away
  • IIFE
  • “let”
Invoke the function, and storing the value

This is about invoking the function right away, and then assigning the value to people[i][“id”].
As you can see when you call creator(gang), the logs ‘Calculating for index:…’ gets called right away.
Because at each index, the anonymous function gets invoked and then the value is stored.

Thus, whenever you access updatedGang[0].id, you’re simply retrieving the stored value

In this solution, we’re invoking the function RIGHT AWAY, thus creating the scope, and the i is accessed. It will return 0. 0 + 100 = 100. It will then assign the integer 100 to updatedGang[0].id
When i becomes 1, the function executes RIGHT AWAY, creating the scope, and the i is accessed as 1. 1 + 100 = 101. 101 gets assigned to updatedGang[1].id.

… and so on.

using IIFE

As you can see, we now have reference to a function that you can execute in the future. In addition, we also have our own variable ‘index’ to store the i.

The IIFE for index 0 puts the i in its own memory, and stores it.
The IIFE for index 1 puts the i in its own memory, and stores it
…etc

Thus, we can invoke on the fly and still get the correct answer. It is vastly different than our previous example, which is invoke right away, and storing the result.

In other words:

Using IIFE, we first create a function expression and invoke it immediately with a parameter. This creates a context that gets pushed onto our stack context.

Creation Phase:
– We point this reference to global object.
– We create outer reference to scope
– puts parameter ‘index’ in memory
– put anon function j in memory.

Execution Phase:
– We use scope to access people and i. We assign them to anon function which is in memory. This anon function will access parameter ‘index’, which is also stored in memory.

Then this IIFE gets popped from the context stack.
When this loop is done, creator context is popped from the stack.

In the future, when you try to access updatedGang[1].id(), you execute this anon function that is stored in memory. It has index as 1, which is also stored in memory.
Hence that is the reason why we’re able to get the correct value at a later time. We store everything in memory via function definitions and variables.

Using let (block scoped)

We need to use let to make sure we get correct scoping.

A variable declared by let or const has a so-called temporal dead zone (TDZ): When entering its scope, it can’t be accessed (got or set) until execution reaches the declaration.

i in the inner function is not referencing some global var i. It it referencing a block scope variable i, which has been pushed onto the local stack.

it works because, for (let i = 0; i < arr.length ;i ++) defines i as var i for the local block.

in addition:

ref – http://chineseruleof8.com/code/index.php/2017/10/01/let-vs-var-js/

i is only visible in here (and in the for() parentheses)
and there is a SEPARATE i var for each iteration of the loop

like this:

does this:

Hence when we call people[0].id(), we evaluate i, which accesses its local var i as 0. 0 + 100 = 100.
people[1].id(), we evaluate the i, which accesses its local var i as 1. 1 + 100 = 101.
… so on.

Another example

Mark and Sweep algorithm for GC

http://www.cnblogs.com/tekkaman/archive/2012/07/05/2578131.html
http://stackoverflow.com/questions/24799297/circular-reference-memory-leak/24963376#24963376

This algorithm reduces the definition of “an object is not needed anymore” to “an object is unreachable”.

  This algorithm assumes the knowledge of a set of objects called roots Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

  This algorithm is better than the previous one since “an object has zero reference” leads to this object being unreachable. The opposite is not true as we have seen with cycles.

  As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when “an object is not needed anymore”.

Cycles are not a problem anymore

In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object. Consequently, they will be found unreachable by the garbage collector.

The same thing goes with the second example. Once the div and its handler are made unreachable from the roots, they can both be garbage-collected despite referencing each other.

Limitation: objects need to be made explicitly unreachable

Although this is marked as a limitation, it is one that is rarely reached in practice which is why no one usually cares that much about garbage collection.

Javascript GC

Currently, Javascript V8’s garbage collection algorithm adopts the mark and sweep algorithm.
Hence, you do not have to worry about circular references.

Modern JavaScript implementations perform garbage collection through a “mark and sweep” algorithm. First they scan through your web app’s entire memory structure starting from the global object, and mark everything they find. Then they sweep through every object stored in memory and garbage collect anything that wasn’t marked. As long as there isn’t a reference to your object from the global object or any stored function, it can be garbage collected.

In Apple’s xCode, the obj-c garbage collector does not. Hence you DO NEED to worry and eliminate any code that has a circular reference, which includes parent/child, blocks, and delegates.

Javascript copy by reference

With a = {}; b = a, you get

quoted from stackoverflow:

No, JS doesn’t have pointers.

Objects are passed around by passing a copy of a reference. The programmer cannot access any C-like “value” representing the address of the object.

Within a function one may change the contents of an passed object via that reference, but you cannot modify the reference that the caller had, because your reference is only a copy:

Pictorial

js_ref_1_2

js_ref_3

js_ref_4_5

splice

Basic Usage

1st param – what index of the array to start
2nd param – how many elements to remove

in firebug console, we first see what test is. Which gives us the result of the full array. Then we do test.splice(1,2), which means at index 1, we remove 2 elements. This returns us “two” and “three”, meaning we removed “two” and “three.

Then we see the results of test again to ensure that “two” and “three” are removed from the original array.

> test
Array [ “one”, “two”, “three”, “four”, “five”, “six” ]
> test.splice(1,2)
Array [ “two”, “three” ]
> test
Array [ “one”, “four”, “five”, “six” ]

in firebug console, we start at index 2, which would be “ten”.
We remove 2 elements, which would be the “ten”, and “six”. The removed elements are returned.
We then add the word “nine”.

> test
Array [ “one”, “four”, “ten”, “six” ]
> test.splice(2,2,”nine”)
Array [ “ten”, “six” ]
> test
Array [ “one”, “four”, “nine” ]

Using splice in List implmentation

We first make a List class default constructor. we initialize member variables. Then we assign function definitions append, remove, length, insert, clear, and toString.

delete the array of elements. then reassign to empty array.

We loop through all the elements of our dataStore array, and if the elements match, we simply return the index.

We first get the index of where we want to remove the element.
Then when we have the index, we use the index as parameter for the splice index to know where to start. The 1 at the 2nd parameter of the splice, means to remove 1 element at that index.

We insert at given position pos, removing 0 elements, and insert the element to be inserted.

DOM

ref – http://www.w3schools.com/js/js_htmldom.asp
https://javascript.info/dom-navigation

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

html = document.documentElement
The topmost document node is document.documentElement. That’s DOM node of tag.
body = document.body
Another widely used DOM node is the element – document.body.
head = document.head
The head tag is available as document.head.

A script cannot access an element that doesn’t exist at the moment of running.

In particular, if a script is inside , then document.body is unavailable, because the browser did not read it yet.

So, in the example below the first alert shows null:

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

HTML DOM methods are actions you can perform (on HTML Elements)

HTML DOM properties are values (of HTML Elements) that you can set or change

for example:

In the example above, getElementById is a method, while innerHTML is a property.

The getElementById Method

The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id=”demo” to find the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML elements.

The HTML DOM Document

In the HTML DOM object model, the document object represents your web page.

The document object is the owner of all other objects in your web page.

If you want to access objects in an HTML page, you always start with accessing the document object.

Below are some examples of how you can use the document object to access and manipulate HTML.

Event for Elements

Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript

Examples of HTML events:

When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key

HTML Event Attributes

Assign Events Using the HTML DOM

DOM collections are read-only

DOM collections, and even more – all navigation properties listed in this chapter are read-only.

We can’t replace a child by something else assigning childNodes[i] = ….
Changing DOM needs other methods, we’ll see them in the next chapter.

DOM collections are live

Almost all DOM collections with minor exceptions are live. In other words, they reflect the current state of DOM.

If we keep a reference to elem.childNodes, and add/remove nodes into DOM, then they appear in the collection automatically.

Siblings are nodes that are children of the same parent. For instance, and are siblings:

body is said to be the “next” or “right” sibling of head,
head is said to be the “previous” or “left” sibling of body
The parent is available as parentNode.

The next node in the same parent (next sibling) is nextSibling, and the previous one is previousSibling.

For instance:

Access the div DOM node, ul DOM node, and 2nd li node

output:

Using console.dir to view objects

We want to color the cells in the table diagonally. In order to do this, we must get the rows object from the table first. The rows property is an array with rows.

For each row object, we see that there is an array of td objects. We color 0th td object for the first row, 1st td object for 2nd row…and so forth.

Javascript scope

ref – http://www.w3schools.com/js/js_scope.asp
ref – https://stackoverflow.com/questions/17279437/lexical-scope-closures-in-javascript
ref – http://adripofjavascript.com/blog/drips/emulating-block-scope-in-javascript.html
ref – https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

JavaScript has two scopes: global and local.

variables declared outside of your function…

Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code.

variables declared inside of your function…

Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions.

Because local scope in JavaScript is created by functions, it’s also called function scope. When we put a function inside another function, then we create nested scope.

Currently, JavaScript, unlike many other languages, does not support block level scoping. This means that declaring a variable inside of a block structure (like a for loop), does not restrict that variable to the loop. Instead, the variable will be accessible from the entire function.

It’s worth noting that the upcoming ECMAScript 6 will support block level scopes via the let keyword.

Lexical Scope

In Paris, I want to print “myFriend”. So I start my searching from there. When I can’t find her in Paris I go one level up and expand my searching in all of France. But again, she is not there. Next, I expand my searching again by going another level up. Finally, I found her in Italy, which in our case is the local scope of Europe.

In the previous example my friend Monique is represented by the variable myFriend. In the last line we call the europe() function, which calls france(), and finally when the paris() function is called, the searching begins. The JavaScript interpreter works from the currently executing scope and works it way out until it finds the variable in question. If the variable is not found in any scope, then an exception is thrown.

This type of look up is called lexical (static) scope.

The static structure of a program determines the variable scope. The scope of a variable is defined by its location within the source code, and nested functions have access to variables declared in their outer scope. No matter where a function is called from, or even how it’s called, its lexical scope depends only by where the function was declared.

Shadowing

If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function. This type of behavior is called shadowing. Simply put, the inner variable shadows the outer.

That’s the exact mechanism used when a JavaScript interpreter is trying to find a particular variable. It starts at the innermost scope being executed at the time, and continue until the first match is found, no matter whether there are other variables with the same name in the outer levels or not.

Additional Material

To put it simply, a scope is the lifespan of a variable. You see, every variable is born, lives and dies. The beginning of a scope marks the time the variable is born and the end of the scope marks the time it dies.

The scope in the previous example was a block scope. It’s just a block of code. Hence the name. Block scopes are immediately executed.

Function scopes on the other hand are templates of block scopes. As the name suggests a function scope belongs to a function. However, more precisely, it belongs to a function call. Function scopes do not exist until a function is called.

Using var, JavaScript only has function scopes. Using let, it has block scopes.

If we are not using let, we can use IIFE to emulate block scoping.
Let’s take a look at an example.

Simulating block scoping with IIFE (Implicit Invoked Function Expression)

In the global scope, we have variables avatar, element, and an array elements.

Then we have a for loop, which is a block. However, before ‘let’, JS do not have block scoping.
Any variables declared inside a block, is scoped to the nearest function.

In JavaScript, variables declared with var are scoped to the nearest parent function.

Hence in our case, when we declare “var element”, it gets scoped to the nearest parent function.
Since element was already declared, the element in the for loop block reference the element in its parent scope. That’s why after the for loop,
var element will have “Water”.

And the output would be: “Ang’s primary element is Water”.

Solution

What we expect is element to be “Air”. Hence, in order for this to happen, we must imitate block scope by using
IIFE like so:

So what we did here is that in the for loop. We first defined an anonymous function.

When the function is defined, a closure is created. It can reference its own scope, parent’s scope, and global scope.

For example, the elements array can be accessed as it is its parent’s scope.

Notice the anonymous function has () at the end. This is executing the anonymous function. We we execute the function, scope is created. This means at the start of the function execution, variables is alive, and when the function exists, the variable die.

Since variables declared with var are scoped to the nearest parent function.

The var “element” is scoped to our anonymous function.

That’s why var element only exists here. For every pass of the loop, we have a scope with its own variable element.

That element references global scope var “elements”.
It logs it, then exits.

When we are done with the for loop, our scope is global, where element still has data “Air”.

The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

Global variables are deleted when you close the page.

local scope

Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.

Local variables are created when a function starts, and deleted when the function is completed.

global scope

A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.

auto global

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare carName as a global variable, even if it is executed inside a function.

Global Variables in HTML

With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object: All global variables belong to the window object.

Closures example

ref –

  • https://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/
  • http://chineseruleof8.com/code/index.php/2015/08/05/self-invoking-anonymous-functions/

Every JavaScript function forms a closure on creation.

Thus, the add variable takes on a function closure. A closure is a function to which the variables of the surrounding context are bound by reference.

In our example, variable counter is declared within the function. And this variable is accessed via reference inside of our return function where counter is incremented.

Keep in mind that the return function acts as a template. When we press the button, the onClick event is passed.

Notice that the IIFE creates a closure and executes down the line: it logs, sets up variable counter to 0, then returns a function reference.

Hence, add is a reference to the returned function.
The returned function has a reference to counter. This is the closure.
All closures in javascript have a dictionary which it keeps track of all the things it has to reference.

When add executes

It will execute the inner function, and return counter + 1.

Problem Example

Let’s take this example.

The function creates a closure, which keeps track of all variables at its outer lexical environment by using a dictionary.

n is passed in the parameter. But i passed through its lexical environment. So we keep track of it.

Say i is a loop’s index:

when the loop is run, it assigns its elements like so:

fns[1] = (function(n)…
fns[2] = (function(n)…
fns[3] = (function(n)…
fns[4] = (function(n)…

When we execute the fns functions, the inner function is a closure with a dictionary for its lexical scope which references i.

For example when fns[1](7) is formed, it will be like so:

The situation is that the lexical environment dictionary will keep reference to i, which is 1 now. But when the loop goes to 2, the i here is 2. So on and so forth.

Let’s see what happens when we start executing these functions:

At the time of execution, i will be 4. And when the fns function executes, it will access i, and i will be 4.

Possible Solution

Since every function invocation takes place in a unique execution context, what we can do to fix the problem so that adders[1][7] = 8, is to execute our function at the time of form via IIFE:

Due to IIFE executing the function at the time of function creation, the i will be index.

This means that which at the time of assignment, whatever number is being used in the parameter of the function closure, is whatever i will be used in the return i + n.

thus, fns[1](7) = 1 + 7.

see here

Prototype Pattern js

ref – https://carldanley.com/js-prototype-pattern/