Closure in JavaScript - Whats Wrong

Javascript Closures - What are the negatives?

You may get a raft of good answers. One certain negative is the Internet Explorer circular reference memory leak. Basically, "circular" references to DOM objects are not recognized as collectible by JScript. It's easy to create what IE considers a circular reference using closures. Several examples are provided in the second link.

  • Microsoft KB Article re IE6 Memory Leak
  • Mitigation Efforts in Later Versions

In IE6, the only way to reclaim the memory is to terminate the whole process. In IE7 they improved it so that when you navigate away from the page in question (or close it), the memory is reclaimed. In IE8, DOM objects are better understood by JScript and are collected as you'd expect they should be.

The suggested workaround for IE6 (besides terminating the process!) is not to use closures.

Is the definition of JavaScript closures on MDN wrong?

MDN is correct, a closure is the combination of a function and its reference to its external environment (which allows it to access the contents of that environment). See also the Wikipedia entry. (Loosely speaking, a closure is a function that has a reference to its outer environment.)

The text you've quoted from elsewhere on SO seems slightly off, but concepts are hard to explain.

But if MDN is right,

var a=1;
function printA(){
console.log(a);
}

this code include a function printA() and its lexical environment(variable a), does it mean this code is closure?

Yes. In fact, all functions in JavaScript are closures (or perhaps more precisely, all functions are associated with closures). That's how global variables work, because all functions are closures over the global lexical environment.


As an implementation optimization, a JavaScript engine can sometimes optimize away the function's link to the external lexical environment, such as here:

function double(a) {
return a * 2;
}

Nothing in double refers to any identifer that isn't defined within the lexical environment created for the call to double, so smart engines can (and do) optimize away the link entirely. Other times, they can determine that only parts of the external environment are used and so only retain those, allowing others to be garbage collected.

JavaScript Closure incorrect behavior

According to this other answer on SO:

a closure is a stack frame which is allocated when a function starts its execution...

So every function call creates its own closure.

What forEach does is that it takes a function (callback) and call it multiple times (passing the element from the array along with its index and the array). So, each iteration of forEach creates a new closure.

You are defining someFn on the first iteration (never get redeclared after that), so the closure it is trapped in is the closure of the first iteration. Thus the only available values are the ones on the first iteration.

The closure is not related to the function itself, it is related to its calls.

Example:

function theFunction(value) {  return function() {    return value;  };}
var someFn1 = theFunction("Ibrahim");var someFn2 = theFunction("John");
console.log("someFn1: ", someFn1());console.log("someFn2: ", someFn2());

Wrong parameter value in JavaScript function

In console list return with a ID of list. And if any variable declared inside a function,it only accessible by that function,it will not available outside of this function. Please read this doc to know further more about function

What am I doing wrong on this simple Closure

you are using the closure in the wrong way...i can't give you a guru type answer as to what was actually happening but here is a working (didn't test it) closure:

inner_link.onclick = (function(link_num){
return function(){
alert('You clicked link '+link_num);
};
})(i);

How do JavaScript closures work?

A closure is a pairing of:

  1. A function and
  2. A reference to that function's outer scope (lexical environment)

A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.

If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret:

function foo() {
const secret = Math.trunc(Math.random() * 100)
return function inner() {
console.log(`The secret number is ${secret}.`)
}
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`

deeper understanding of closure in Javascript

I think you're taking that comment too literally. The comment is just saying that you can't access it outside the function scope (it's not publicly accessible), not that its not available at all within the function. The returned function will have access to all of the outer functions scope no matter what. You just can't access that scope outside the outer function if the inner function doesn't provide a way of accessing it.

For instance, this expression evaluates to 4:

function testClosure(){
var x = 2;
return function(y){
alert(eval(y));
}

}

var closure = testClosure();

closure("x+2"); //4

http://jsfiddle.net/dmRcH/

So x is available despite not being directly referenced

Further research

It appears that chrome and firefox at least do attempt to optimize this in the sense that if you're not providing ANY way to reference the x variable, it doesn't show up as being available in the debugger. Running this with a breakpoint inside a closure shows x as unavailable on Chrome 26 and Firefox 18.

http://jsfiddle.net/FgekX/1/

But thats just a memory management detail, not a relevant property of the language. If there is any possible way that you could reference the variable, it is passed, and my suspicion is that other browsers may not optimize this in the same way. Its always better to code to the spec than to an implementation. In this case though the rule really is: "if there's any possible way for you to access it, it will be available". And also, don't use eval because it really will keep your code from optimizing anything.

Is it true that every function in JavaScript is a closure?

Is the function created by Function constructor also a closure?

Yes, it closes over the global scope. That might be unintuitive because all other JavaScript closures close over their lexical scope, but it still matches our definition of a closure. In your example, a is a free variable, and resolves to the a in an other scope when the inner/fn function is called somewhere.

If an inner function doesn't have any free variables, can we still call it a closure?

Depends on whom you ask. Some say Yes, others call them "uninteresting closures", personally I say No because they don't reference an outer scope.

What exactly does closure refer to in JavaScript?

From JavaScript Closures

Two one-sentence summaries:

A closure is the local variables for a
function - kept alive after the
function has returned, or

A closure is a stack-frame which is
not deallocated when the function
returns. (as if a 'stack-frame' were
malloc'ed instead of being on the
stack!)

A very good article on closures

Javascript Closures

A "closure" is an expression
(typically a function) that can have
free variables together with an
environment that binds those variables
(that "closes" the expression).

The simple explanation of a Closure is
that ECMAScript allows inner
functions; function definitions and
function expressions that are inside
the function bodies of other functions.
And that those inner functions are
allowed access to all of the local
variables, parameters and declared
inner functions within their outer
function(s). A closure is formed when
one of those inner functions is made
accessible outside of the function in
which it was contained, so that it may
be executed after the outer function
has returned. At which point it still
has access to the local variables,
parameters and inner function
declarations of its outer function.
Those local variables, parameter and
function declarations (initially) have
the values that they had when the
outer function returned and may be
interacted with by the inner function.

A good example over here

JavaScript, time to grok closures



Related Topics



Leave a reply



Submit