JavaScript scoped closures (JavaScript you don't know)

Source: Internet
Author: User
Tags closure

JavaScript closures are the knowledge that JS development engineers must gain in-depth understanding. In March, I wrote a blog, "JavaScript closures," the blog is simply a description of the closure of the work process and a few examples, and did not go into the inquisitive, to understand it!

now, with a more in-depth understanding of JavaScript, and just finished reading the book, " You Don't know the JavaScript (roll up)", so take the opportunity to sort it out from the bottom and the principle.

JavaScript does not have a dynamic scope, it has only lexical scopes. Lexical scopes are determined when writing code or definitions, while dynamic scopes are determined at run time. Before we know about closures, we first need to know what the lexical scope is (the scope is determined by the position of the function declaration when the code is written).
One, what is closed packageExample 1:
function foo () {var a = 2;function bar () {Console.log (a);} return bar;} var baz = foo (); Bzz (); 2
After Foo () is executed, it is generally assumed that the garbage collection mechanism will destroy the entire internal scope of Foo (), while closures can prevent this from happening, allowing its internal scope to persist. Because bar () is inside Foo (), it has a closure that covers the Foo () scope, allowing the scope to remain alive for the bar () to be referenced at any later time.

Bar () still holds a reference to the scope, and this reference is called Closed Package
in short: When a function can remember and access its lexical scope, even if the function executes outside the current lexical scope, a closure is generated.
Example 2:regardless of how the value of a function type is passed, closures can be observed when the function is called elsewhere.
function foo () {var a = 2;function Baz () {console.log (a);} Bar (baz);} Function Bar (FN) {fn ();//This is the closure}
Example 3:Pass an intrinsic function (timer) to the settimeout. The timer has a closure that covers the wait () scope, preserving a reference to the variable message.
After wait () executes for 1000 milliseconds, its scope does not disappear, and the timer retains the wait () scope closure.
function Wait (message) {SetTimeout (function timer () {console.log (message);},1000);} Wait ("Hello,ligang");
Example 4:The following activator () have closures covering the Setupbot () scope!
function Setupbot (name, selector) {$ (selector). Click (function Activator () {Console.log ("activating:" + name);}); Setupbot ("Closure bot 1", "#bot_1"), Setupbot ("Closure bot 2", "#bot_2");
ii. circulation and closures
for (var i=1; i<=5; i++) {setTimeout (function timer () {console.log (i);}, i*1000);} Expected: Frequency output once per second 1~5//results: Frequency output once per second five times 6
First explain: "i*1000", 5 timing respectively in 1s, 2s, 3s, 4s, 5s after the implementation, not 1s, 3s, 6s, 10s, 15s. That is, the frequency is 1s, not each interval increases by 1s. If I is removed as "1000", it will be output five times after the for execution of the 1s 6.

The callback function is executed at the end of the loop, so the output is a cyclic termination condition that is the I value. In factwhen the timer is running, even if settimeout (..., 0) is executed in each iteration, all callback functions are still executed at the end of the loop.
Depending on how the scope works, although five functions are defined separately in each iteration, they are all enclosed in a shared global scope, so there is actually only one I.
Solution 1:
for (var i=0; i<=5; i++) {(function (j) {SetTimeout (function timer () {console.log (j);}, j*1000);}) (i);} Result: Frequency output once per second
Each iteration generates a new scope, allowing the callback of the deferred function to enclose the new action within each iteration, and each iteration will contain a variable with the correct value for our access.
Solution 2 (ES6):
for (var i=0; i<=5; i++) {Let j = i;settimeout (function timer () {console.log (j);}, j*1000);} Result: Frequency output once per second


for (let i=0; i<=5; i++) {setTimeout (function timer () {console.log (i);}, i*1000);} Result: Frequency output once per second five times 6

third, the module

modules need to have two prerequisites:

(1) There must be an external enclosing function that must be called at least once (each call creates a new instance of the module).

(2) The enclosing function must return at least one intrinsic function in order for the inner function to form a closure in the private scope and to access or modify the private state.

Typical modularity:
function Coolmoudle () {var something = "cool"; var dosomething = function () {console.log (something);} Return{dosomething:dosomething};} var foo = Coolmoudle ();//If the external function coolmoudle () is not executed, neither the inner scope nor the closure can create foo.dosomething ();//cool
Single-case mode:
var foo = (function coolmodule (ID) {function change () {//Modify public apipublicapi.identify = Identify2;} function Identify1 () {console.log (id);} function Identify2 () {Console.log (Id.touppercase ());} var Publicapi = {Change:change,identify:identify1};return publicapi;}) ("foo module"); Foo.identify ();//foo modulefoo.change (); foo.identify (); FOO MODULE

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaScript scoped closures (JavaScript you don't know)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.