Are they considered closing Javascript?

The desire to get something right here ... so I have 2 questions

The function below creates a closure.

function Foo(message){ var msg = message; return function Bar(){ this.talk = function(){alert(msg); } } }; 

Q: Which function is closing, Foo or Bar ?
I always thought that the closure should be Foo , because it closes above Bar after Bar returns.

Further...

The following is a definition of an anonymous function:

 ()(); 

Q: Is the inner function inside this anonymous function closure?

 (function(){ /* <-- Is this function also a closure? */ })(); 
+6
source share
2 answers

Here you need to use the first principles. Javascript uses lexical reach. This means that the scope of the execution context is determined by how the code is defined (lexical).

I would say that defining the Bar function is what causes the closure to create, because msg is "closed" in the function.

The actual creation of the closure occurs at run time (which is somewhat a tautological statement, since nothing happens in the computer program before it starts), because to determine the msg value in Bar when Bar is executed, the interpreter must know the value of the variable when Foo executed, and so on the chain.

I will give two answers to your question. The pedantic answer: none of the functions in itself is a closure. This is the definition of variables within functions in combination with the context of the execution of functions when they are launched, which defines the closure. General answer: any function that closes above a variable is a closure (Bar in your case).

Consider the problem everyone faces when using Javascript.

 function A(x) { var y = x, fs = []; for (var i = 0; i < 3; i++) { fs.push(function(){ console.log (i + " " + x); }) } fs.forEach(function(g){g()}) } A('hi') 

Most people would say that this would print "hi 1" followed by "hi 2" and then "hi 3". However, he produces "hi 3" 3 times. If only the definition of the function to be added to the array, using the variables defined in the external function, created a closure, how can this be?

This is because you need an execution context to define a closure that is not executed before execution. When executing functions in the array i has a value of 3 . The forEach statement has this execution context, so the output always uses 3.

+4
source

Bar is a closure.

We say that Bar closes the msg variable in its environment.

More often than not, closing a word means: a function that uses at least one variable defined in the enclosing area, in the closing function.

To answer your second question: (function(){ ... })() is what it looks like: one anonymous function, not two. If it is not nested in another function, you usually do not call it closure. However, functions nested inside this anonymous function may be closed (and often).

+1
source

Source: https://habr.com/ru/post/923291/


All Articles