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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With