Home Web Front-end JS Tutorial A brief discussion on Javascript closure based on a piece of code_javascript skills

A brief discussion on Javascript closure based on a piece of code_javascript skills

May 16, 2016 pm 06:13 PM
javascript Closure

Copy code The code is as follows:

function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return f2;
}

The closure here is f1, which closes a variable n and a function f2.

Let’s ignore nAdd first and try to keep the original appearance and rewrite this function.
Copy code The code is as follows:

function f1(){
var n = 999 ;
var f2 = function(){ alert(n); };
return f2;
}
var result = f1();
result();

Each variable in js is encapsulated in a function unit. When a variable is not found inside the function, the function will search in the previous unit (context) where it is located, all the way to the top-level window domain. .
A question arises at this time: Does the search process start from the function reference position or the function body definition position?
In the above code, the domain of result is window, but the actual output result is the n value inside f1, so it can be concluded that the starting point of variable search is the position where the function body is defined.

Now look back at nAdd (the first piece of code). As we know, variables defined without the keyword var enter the window domain by default, so nAdd is actually window.nAdd. This is equivalent to the following code:
Copy the code The code is as follows:

var nAdd;
function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return function(){ alert(n); };
}

Then according to our analysis of result, the execution of nAdd will affect the value of n in f1.
So there is:
Copy the code The code is as follows:

function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return function(){ alert (n); };
}
var result = f1();
result();
nAdd();
result();

The final output result of this code execution is 1000.

Look at this situation again:
Copy the code The code is as follows:

function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return function(){ alert(n); };
}

f1()(); //<--p1
nAdd();
f1()() ; //<--p2

Briefly describe the execution process:
At position p1, f1 encapsulates an anonymous closure A, and returns the function A:f2 in the closure of A. Then A:f2 is executed, A:f2 outputs variable A:n, and the result is 999.
At the same time, nAdd is assigned as a function in the closure of A, and the next line executes nAdd to set the value of A:n to 1.
At position p2, f1 encapsulates the anonymous closure B. The operations performed are all for closure B. Then the output of B:f2 is B:n, so the final result is still 999.
A and B are two independent "packages" and do not affect each other.

Rewrite the calling part of the function:

Copy the code The code is as follows:

function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return function(){ alert(n); };
}

var result = f1();
result();
nAdd();
f1()();
result(); // <--p3

The p3 position unexpectedly outputs 1000.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

The role of golang function closure in testing The role of golang function closure in testing Apr 24, 2024 am 08:54 AM

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.

Summary of the advantages and disadvantages of golang anonymous functions and closures Summary of the advantages and disadvantages of golang anonymous functions and closures May 05, 2024 am 09:54 AM

Anonymous functions are concise and anonymous, but have poor readability and are difficult to debug; closures can encapsulate data and manage state, but may cause memory consumption and circular references. Practical case: Anonymous functions can be used for simple numerical processing, and closures can implement state management.

See all articles