Does the anonymous function in Foo
get re-created in memory each time Foo()
gets called?
function Foo(product)
{
return function(n) {
return n * product;
}
}
I'm more or less interested in V8's implementation in particular, since I'm not seeing anything in regards to that in the spec (unless I'm missing something, which I probably am).
I'm kind of confused on the memory management going on since the use of product
is specific to the closure that is returned; however, that doesn't necessarily say the inner function has to be re-created along with a closure instance (in theory), since you can still .bind()
without losing closure values.
As far as I know a new function object gets re-created everytime, but the function's code (body) is normally getting reused. I do not know under what circumstances it wouldn't be however.
https://groups.google.com/forum/#!topic/v8-users/BbvL5qFG_uc
This code snippet shows that you're getting a new Function object each time:
function Foo(product)
{
return function(n) {
return n * product;
}
}
var a = Foo(2);
var b = Foo(2);
alert(a === b); // alerts false
Demo: http://jsfiddle.net/wc5Lv/
There are probably interpreter optimizations that can internally reuse the parsed function, but from the pure javascript point of view, a new Function is created each time.
Yes. The ECMAScript specification, 5ed, requires that each evaluation of a function expression or function declaration generates a new function object. If you read the cases of http://es5.github.io/#x13 they all contain the phrase "a new Function object"
That just means that there is a new Function object, but most of the internal content of that function object can be shared between instances, including the code generated for the function body. The new object only needs to hold the value of the product
variable and a reference to the shared function implementation.
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