Monthly Archives: January 2016

Using closures with this


~~~entered clickHandler~~~
The Masters
——— T. Woods ———
——— P. Mickelson ———


ref –

that all functions in JavaScript have properties, just as objects have properties.
And when a function executes, it gets the ‘this’ property.

a variable with the value of the object that invokes the function where this is used.

The this reference ALWAYS refers to (and holds the value of) an object(a singular object) and it is usually used inside a function or a method, although it can be used outside a function in the global scope.

Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.


If you understand this one principle of JavaScript’s this, you will understand the “this” keyword with clarity:

“this” is not assigned a value until an object invokes the function where “this” is defined.

Let’s call the function where this is defined the “this Function.”

Even though it appears this refers to the object where it is defined, it is not until an object invokes the this Function that this is actually assigned a value. And the value it is assigned is based exclusively on the object that invokes the this Function. this has the value of the invoking object in most circumstances. However, there are a few scenarios where this does not have the value of the invoking object.

this in Global scope

In the global scope, when the code is executing in the browser, all global variables and functions are defined as attributes on the window object.

Therefore, when we use this in a global function, it refers to (and has the value of) the global window object (not in strict mode though, as noted earlier) that is the main container of the entire JavaScript application or web page.

this on global scope example

continuing on with the example…

continuing on with the example…

Closures (js)

First, let’s discuss Variable Scope

A variable can be defined in either local or global scope, which establishes the variables’ accessibility from different scopes during runtime.

Any defined global variable, meaning any variable declared outside of a function body will live throughout runtime and can be accessed and altered in any scope.

Local variables exist only within the function body of which they are defined and will have a different scope for every call of that function. There it is subject for value assignment, retrieval, and manipulation only within that call and is not accessible outside of that scope.

The Scope Chain

Whenever a function is executed, it creates scope.

In others, a function execution is called an execution context. The execution context creates a scope chain.

The scope chain contains the variable object for every execution context in the execution stack. It is used for determining variable access and identifier resolution.

For example

Then first call executes, its execution context gets pushed onto the stack. It calls function ‘second’,
Then second call executes, which gets pushed onto the execution stack…and so on.

Each scope chain that gets pushed onto the execution stack has a variable access.

At this point the scope chain would be, from top to bottom of the execution stack would be:

The fourth function would have access to global variables and any variables defined within the first, second, and third functions as well as the functions themselves.


— start first —
— start second —
— start third —
— start fourth —
global variable
third’s name
— end fourth —
— end third —
— end second —
— end first —

Notice third’s name in the output.

Name conflicts amongst variables between different execution contexts are resolved by climbing up the scope chain, moving locally to globally. This means that local variables with the same name as variables higher up the scope chain take precedence.

To put it simply, each time you attempt to access a variable within a function’s execution context, the look-up process will always begin with its own variable object. If the identifier is not found in the variable object, the search continues into the scope chain. It will climb up the scope chain examining the variable object of every execution context looking for a match to the variable name.

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:

1 second later…


not really what we want…

2nd try

Now let’s execute the callback function right away. The i referenced in the callback is still from the parent scope.
thus, the result be:

for loop: 0
callback: 0 √
for loop: 1
callback: 1 √

Now the output is:

for loop: 0
callback: 0 √
for loop: 1
callback: 1 √
for loop: 2
callback: 2 √

So we have both console log being executed right away

But the thing is, we’re not giving setTimeout a function to process after the 1 second. Our goal is to give it a function
the execute after 1 second has elapsed.

3rd try

Let’s pass the var i into the callback function as a parameter.
The trick is. i’s value is received via scoping when the callback fun executes.

Then the callback function in setTimeout will have their own execution context like so:

…. so on.

When that happens, the parameter variable is tied to that function’s execution context.
Thus, any inner functions that references its parent scope, will be able to get the unique i
via parameter index.

for loop: 0
callback: 0 √
for loop: 1
callback: 1 √
for loop: 2
callback: 2 √
for loop: 3
callback: 3 √


inner func: 0
inner func: 1
inner func: 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


Things can get weird though

Here we pass an array into a function. We use a loop to assign index to the array element’s id property.

After we run this, the result id are all the same, 103.
The reason why is because the anonymous function is simply defined. Thus, all it has is a closure. It simply means when the function is executed, it can reference variables in scope.

When we do execute the anon function it later, scope is then created. We access the i, but it has already ran to 3. Thus, that’s why the id
for all three people are at 103.


We need to make sure we get correct scoping. We do this through:

  • “Invoke the function”
  • or using “let”
Invoke the function

FIRST, notice that the log inside of the anon function never logs. That’s because we don’t invoke the function. When we don’t invoke the function, we do not create scope. Remember, when defining a function, closure is created. When invoking a function, scope is created. Since we never invoked the function, no scope was ever created.

Use an Immediately Invoked Function Expression (IIFE) to invoke the function right when the assignment of the closure to the id happens.

That way, after the assignment, the function gets executed right away.

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 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 –

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.

callback example – executed right away

Closure definition

The closure is first defined through its definition when you call makeFunc() at line 1.
It runs through standard code. If it has function definitions, it DOES NOT run them. It simply acknowledges them and readies them for use.

That why when you call makeFunc() from your calling scope, you’ll see the logs in makeFunc’s scope. But nothing from displayName function.

Hence it runs:

  • ^^^^^^^^ entered makeFunc() closure ^^^^^^^^
  • makeFunc returns function displayName()

In the calling scope, it returns the closure to var myFunc, ready for use.
Hence, you directly call myFunc() when you want to use the closure. Since the definition of the closure returns the function definition displayName(), calling myFunc() will make you run through the logs in displayName().

  • <--  displayName() 
  • name is Mozilla
  •  displayName()  –>

local variables are kept by reference

…and kept in memory via stack-frame.

the local variables are not copied — they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!

For example:

a new closure (stack-frame!) is created

…whenever the closure is called. In JavaScript, whenever you declare a function inside another function, the inside function(s) is/are recreated again each time the outside function is called.


Hence, as you can see, the first time we call setupSomeGlobals(), we have a new closure stack.

We increase the closure’s num, which gives us 667.
Then we alert it.
Then we set that num to 5.
We then have var oldAlert point to the same function gAlertNumber is pointing to. The global var and var oldAlert are pointing to the same function() { alert(num); }.

Take note here that this function() {alert(num);} takes place in the the 1st closure.

Then, we call setupSomeGlobals again. This time, a new closure is created (2nd one). All three functions are created within the closure, and the global variables gSetNumber, gIncreaseNumber, gAlertNumber now repoints to new functions in our 2nd closure.

Keep in mind that the var oldAlert is still pointing to the alert function in the first closure.

That’s why after the 2nd setupSomeGlobals(),

when you call gAlertNumber(), you get 666, because the global variable repoints to the newly created function in the 2nd closure.

When you call oldAlert, you get 5, because its pointing to the function in the 1st closure.

Block Property use copy or strong

ref –

Short Answer

The answer is it is historical, you are completely correct that in current ARC code there is no need to use copy and a strong property is fine. The same goes for instance, local and global variables.

Long Answer

Unlike other objects a block may be stored on the stack, this is an implementation optimisation and as such should, like other compiler optimisations, not have direct impact on the written code. This optimisation benefits a common case where a block is created, passed as a method/function argument, used by that function, and then discarded – the block can be quickly allocated on the stack and then disposed of without the heap (dynamic memory pool) being involved.

Compare this to local variables, which
(a) created on the stack
(b) are automatically destroyed when the owning function/method returns and
(c) can be passed-by-address to methods/functions called by the owning function.

The address of a local variable cannot be stored and used after its owning function/method has return – the variable no longer exists.

However objects are expected to outlast their creating function/method. So unlike local variables, objects are allocated on the heap and are not automatically destroyed based on their creating function/method returning but rather based on whether they are still needed (used) – and “need” here is determined automatically by ARC these days.

So what about Blocks?

Creating a block on the stack may optimise a common case but it also causes a problem – if the block needs to outlast its creator, as objects often do, then it must be moved to the heap before its creating method’s local stack is destroyed.

When the block implementation was first released the optimisation of storing blocks on the stack was made visible to programmers as the compiler at that time was unable to automatically handle moving the block to the heap when needed – programmers had to use a function block_copy() to do it themselves.

While this approach might not be out-of-place in the low-level C world (and blocks are C construct), having high-level Objective-C programmers manually manage a compiler optimisation is really not good. As Apple released newer versions of the compiler improvements where made. Early on it programmers were told they could replace block_copy(block) with [block copy], fitting in with normal Objective-C objects. Then the compiler started to automatically copy blocks off stack as needed, but this was not always officially documented.

There has been no need to manually copy blocks off the stack for a while, though Apple cannot shrug off its origins and refers to doing so as “best practice” – which is certainly debatable. In the latest version, Sept 2014, of Apple’s Working with Blocks, they stated that block-valued properties should use copy, but then immediately come clean (emphasis added):

Note: You should specify copy as the property attribute, because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior.
There is no need to “show the resultant behavior” – storing the block on the stack in the first place is an optimisation and should be transparent to the code – just like other compiler optimisations the code should gain the performance benefit without the programmer’s involvement.

So as long as you use ARC and the current Clang compilers you can treat blocks like other objects, and as blocks are immutable that means you don’t need to copy them. Trust Apple, even if they appear to be nostalgic for the “good old days when we did things by hand” and encourage you to leave historical reminders in your code, copy is not needed.