简体   繁体   中英

Will a simple function declaration form a closure in JavaScript?

Will the following code form a closure?

function f() {}

Does where this function is defined affect the answer?

Yes, it forms a closure.

A closure is the combination of a function reference and the environment where the function is created. The code in the function will always have access to any variables defined in the scope where the function is created, no matter how the function is called.

Example; the function f will always use the variable x even if it is called in a scope where x isn't reachable:

 function container() { var x = 42; function f() { document.write(x); } return f; } var func = container(); func(); // displays 42 //document.write(x); // would give an error as x is not in scope 

You create a closure when the function has references to variables in its lexical scope:

var a = 'foo'
function f() {} // no closure
function f() {return a} // closure

If you place a debugger statement inside the function you can see what the closure contains in Chrome devtools. You'll see the first example has nothing, while the second will show a: 'foo'

Yes, it always defines a closure no matter where it is defined. This tutorial has a few illustrative examples.

Because javascript is a special language (see scope, hoisting and more recently the TDZ), depending on how specific you are in your question you might get different answers.

Is it a javascript closure? No. See definition by Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Is it captured in a closure (or does it form a closure - the original question)? Depends on optimizations. But most likely yes. See http://dmitrysoshnikov.com/ecmascript/chapter-6-closures/ and more importantly https://en.wikipedia.org/wiki/Closure_%28computer_programming%29

The closure term is used by javascript "evangelists" to identify those functions that would not work correctly if they weren't captured in actual closures - this is the correct way of saying it from a fundamentally operational point of view. And the reason is probably due to a lack of a better term rather than anything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM