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.
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.
-
1
What does using
.bind()
have to do with not losing the closure values. I'm not understanding your point there. – cookie monster Commented May 24, 2014 at 2:25 -
Was just re-iterating that
Foo(n).bind()
wouldn't changen
in the function returned by the call tobind
. – Qix - MONICA WAS MISTREATED Commented May 24, 2014 at 2:29 - @Downvoter, care to explain? – Qix - MONICA WAS MISTREATED Commented Jun 24, 2014 at 1:04
3 Answers
Reset to default 5As 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./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/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.