Understanding JavaScript Closures

综合技术 2017-12-30

When you’re first learning JavaScript, terms like “closures” may make the language appear mystical and hard to understand. But some of these terms are just sugary concoctions that give fanciful names to very simple concepts. If you’ve spent just a few minutes tinkering with JavaScript, you’ve probably used closures without knowing it. That’s because the JavaScript language depends on closures to create programs that are concise and efficient. By the end of this tutorial, you will gain a full understanding of closures.

What is a closure?

In order to really understand closures, it is helpful to know how scope works. We covered scope in a previous article, so we’ll quote it here:

[I]f you declare a function within another function, you create what’s called a scope chain
. The outer parent cannot see the variables of its child(ren), but the child can see the variables of its parent(s). Confused? Think of a Matryoshka doll. Now imagine if these dolls were given life(scary thought). An outer doll wouldn’t be able to see the gruesome innards of an inner doll. The inner doll can see everything. Now that’s scope.

We can conclude that the inner function has three scope chains
. The first chain allows the inner function to access its own variables. The second allows it to access the variables and parameters of the outer function. And the third allows it to access the global variables. Every time we add a function, we’re adding a new link to the chain.

By defining a function within another function, we create a closure
. Closures themselves can also take on the role of outer functions. Take this somewhat practical example of multiple closures:

In this example, we have two closures. combineName()
is a closure to the outer function of sayMyName()
. getRandomInt()
serves as both a closure to combineName()
and sayMyName()
. What this means is that combineName()
has three scope chains while getRandomInt()
has four scope chains. Every time we create a closure, one link is added to the scope chain. So, getRandomInt()
can access the variables of combineName()
and sayMyName()
.

S
ide Note
: As you can see from the example, we were able to “borrow” the parameters from sayMyName and use them in our first closure, all thanks to the trickle down effect scope chains have, which, *ahem*, is far more reliable than trickle down economics. One point to note, however, is that you cannot call an outer function’s arguments object
from within a closure.

Closures In Depth

We’ve briefly outlined what closures are. Now let’s go through some use cases and explore the deepest depths of closures.

Closures are basically the walking dead.When a function returns, the idea is that all of the variables within that function should be non existent. Yet, closures still have access to any variables in their scope chains.

Here’s an example:

The reason why we can still access the name of this “zombie” isn’t due to any sci-fi magic, it’s because closures don’t store value. Values are static. Instead, they store references to values in their scope chains. The amazing thing is that if you were to change the value of a variable up in the scope chain before returning the closure, the same value used within the closure will then update. This phenomenon is called state,
which is the backbone of programming. We want to be able to create functions whose inner data lives on through the lifetime of our apps. When a user inputs data, we want that data to be updated.

We’ll show an example of how we can use closures to create a modular pattern by modifying our above code:

What we’ve created is an
anonymous closure

by enclosing
our first function within parenthesis.

(function(){…})();

您可能感兴趣的

How do I count the number of unique elements in a ... I have an orders array. orders = ; I want to write a function to count the number of unique table_id or unique food_id in the array. For ...
js 数据类型 我们都知道JavaScript有'字符串','数字','布尔','数组','对象','Null','Undefined'等七种数据类型,但是碰到实际应用场景,很容易搞混淆,傻傻分不清,就没法找到因为变量类型搞错导致的bug。 1,字符串 var abc = "hello"...
BSides CPT Badge 2016 After the fairly successful ZACon badges I did in 2014 , the BSides team in Cape Town (where I now live) asked if I’d like to be involved in bui...
Burp Macros and Session Handling. Burp Macros and Session Handling Home Blog Burp Macros and Session Handling Thurs 25th Jan 18 I've been using Burp Suite ...
Quickly assign JavaScript variables This is one of those questions I don't know how to properly word so I appologize if it has been asked before. Python provides some very simple stat...