Is it true that a closure is created in the following cases for foo
, but not for bar
?
Case 1:
A closure is when free variables in some function code are bound to some values by the function "context" (closure being a more proper term here than context).
Here, i
is a free variable for the function code of foo
. And this free variable is not bound to any particular value by any existing context (closure). So you don't have any closure.
Now to create a closure you have to provide a value-bounding context:
In summary, you can't have a closure unless a function returns another function. In that case, the returned function has all the variable-value bindings that existed in the returning function when it exited.
Concerning your exemples:
this
. When the function is called as member of an object, the object is assigned to the value of this
. Otherwise, the value of this
is the global object.foo
return bar
, you would create a closure that contains only 'bar' and its value : function bar() {}
.