Home > Web Front-end > JS Tutorial > JavaScript closures, it's up to you whether you understand them or not, but I understand them_javascript skills

JavaScript closures, it's up to you whether you understand them or not, but I understand them_javascript skills

WBOY
Release: 2016-05-16 18:00:41
Original
925 people have browsed it

I feel more and more that there is no atmosphere for teaching and educating people in China. In order to understand the closures of JS, I used my CET-4 English skills to search for explanations about closures on Google. When I saw this on stackoverflow After answering an answer, a sentence appeared in my mind: That’s why this guy didn’t run away!

The translation is below, it’s funny.

Peter Mortensen asked:

As old Albert said, "If you can't explain it to a six-year-old, then you don't understand it yourself." Okay. , I tried to teach a 27-year-old friend about JS closure (JavaScript closure) but failed completely.

How would you explain this to a curious six-year-old?

Note: I've seen the examples given on StackOverflow, but they didn't work at all.

Ali’s answer:

When functions are nested within functions, the inner function can access variables in the outer function.

Copy code The code is as follows:

function foo(x) {
var tmp = 3;
function bar(y) {
alert(x y ( tmp));
}
bar(10);
}
foo(2)

No matter how many times it is executed, alert 16 will be issued, because bar can access the parameter x of foo and the variable tmp of foo.

However, this is not a closure yet. When you return an internal function, it is a closure. The inner function will close-over the variables of the outer function until the inner function ends.
Copy code The code is as follows:

function foo(x) {
var tmp = 3;
return function (y) {
alert(x y ( tmp));
}
}
var bar = foo(2); // bar is now a closure
bar(10);

The above script will also eventually alert 16, because although bar is not directly in foo's internal scope, bar still has access to x and tmp.

However, since tmp still exists inside the closure with bar, it will still increase by 1, and it will increase by 1 every time you call bar.

(Considering six This limitation: We can actually create more than one closure method, such as returning their array, or setting them as global variables. They all point to the same x and the same tmp, instead of each having a copy)
Note: Now let’s talk about the seven-year-old content.

The above x is a literal value (value transfer). Like other literal values ​​in JS, when foo is called, the value of the actual parameter x is copied, and the copied copy is used as The parameter x of foo.

Then here comes the problem. When dealing with objects in JS, pass by reference is used. So, if you pass an object when calling foo, the closure of the return function of foo will also refer to the original object!

Copy code The code is as follows:
function foo(x) {
var tmp = 3;
return function (y) {
alert(x y tmp);
x.memb = x.memb ? x.memb 1 : 1;
alert(x.memb);
}
}
var age = new Number(2);
var bar = foo(age); // bar is now a closure that references age
bar(10);

As expected, x.memb will increase by 1 every time bar(10) is run. But it should be noted that x points to the same object variable - age every time. After running bar(10) twice, age.memb will become 2.

This is related to the memory leak of HTML objects. Uh, but it seems beyond the scope of answering the question.

JohnMerlino said to Ali:

Here is an example of a closure without the return keyword:

Copy code The code is as follows:
function closureExample(obj, text, timedelay) {
setTimeout(function() {
document.getElementById(objID).innerHTML = text;
}, timedelay);
}
closureExample('myDiv', 'Closure is created', 500);


Late night 1:37 John Pick answered this:

Functions in JS can access them:

1. Parameters

2. Local variables or functions

3. External variables (environment variables?), including

3.1 Global variables, including DOM

3.2 Variables or functions of external functions.

If a function accesses its external variables, then it is a closure.

Note that external functions are not required. By accessing external variables, a closure can keep these variables alive. In the case of inner and outer functions, the outer function can create local variables and eventually exit; however, if any one or more of the inner functions does not exit after it exits, then the inner function maintains the outer function's local data. .

A typical example is the use of global variables.

mykhal responded like this:

Wikipedia’s definition of closure is as follows:

In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.

Technically speaking, in JS, every function is a closure because it can always access data defined outside of it.

Since scope-defining construction in Javascript is a function, not a code block like in many other languages, what we usually mean by closure in Javascript is a fuction working with nonlocal variables defined in already executed surrounding function.

Closures are often used to create functions that contain hidden data (but not always).
Copy code The code is as follows:

var db = (function() {
/ / Create a hidden object, this object holds some data
// This object cannot be accessed from the outside
var data = {};
// Create a function, this function provides some access to data The data method
return function(key, val) {
if (val === undefined) { return data[key] } // get
else { return data[key] = val } / / set
}
// We can call this anonymous method
// Return this internal function, which is a closure
})();
db('x'); // Return undefined
db('x', 1); // Set data['x'] to 1
db('x'); // Return 1
// We cannot access The data object itself
// But we can set its members

After reading so many answers from foreign experts, I don’t know if you understand it or not, but I understand it anyway.
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template