Question about joined function object of ECMA-262 3rd edition

John Cowan cowan at
Thu Jul 26 08:31:25 PDT 2007

Shijun He scripsit:

> function A() {
>   function B(x) { return x*x }
>   return B
> }
> var b1 = A();
> var b2 = A();
> Spec says: b1 and b2 can be joined, implementation may make b1 and
> b2 the same object because [[scope]] of them have no difference.
> Two call of A() will produce a function from the same FunctionBody, so
> they are equated and the result function objects can be joined, am I
> right? 

It is not because b1 and b2 come from the same FunctionBody, but because
the function B has no persistent state, that they can be joined (which
is just a way of saying they are the same object).  Because A has no
local variables, B doesn't have to care that it was nested inside A.

> function C(x) {
>   function D() { return x*x }
>   return D
> }
> var d1 = C(1);
> var d2 = C(2);
> Are these two call of A() also are equated uses of the same source?

No.  In this case, d1 and d2 have to be different objects, because they
have different persistent states:  within d1, the variable x (which is
free in D) is bound to 1, but within d2, the variable x is bound to 2.
Thus d1 and d2 must be different objects.

In the A-B case, it is not a requirement that b1 and b2 are the same
object, but interpreters are permitted to make this optimization to
save on allocation.  Whether any of them actually do the optimization
is another question.  It may be more trouble than it's worth.  However,
a proper ES compiler would probably want to do so.

We call nothing profound                        cowan at
that is not wittily expressed.                  John Cowan
        --Northrop Frye (improved)

More information about the Es4-discuss mailing list