Strengthening Function.prototype.toString

Eugene Lazutkin eugene.lazutkin at
Sat Oct 11 11:08:08 PDT 2008


Yuh-Ruey Chen wrote:
> So as far as I can tell, what we need to discourage usage of
> func.toString() is:
> 1) An API for function currying/partial evaluation (specializing/binding
> certain arguments).
> 2) A read-only property on functions that contains the list of parameter
> names.

Both points are valid. But #2 is of little utility for variadic 
functions. Example:

function foo(){
   return arguments[5];

As you can see it is generally impossible to know how many arguments are 
actually expected, and what are their names.

Personally I am not against a read-only property for argument names, 
just pointing out its limited utility.

> For any other purpose, I would think that you might as well parse the
> whole source file rather than just the function, since you would need to
> keep track of closures. For example, consider this:
> function foo() {
>     var x = 10;
>     return function() {
>        return x;
>     };
> }
> function bar(f) {
>     var x = 20;
>     print(f());
>     print(eval(f.toString())());
> }
> bar(foo());
> That would print 10, then 20. So as you can see, even in the same scope,
> eval(f.toString())(...) is not necessarily equal to f(), even if
> f.toString() is a correct decompilation of f.

That's a good point about literal comparison of bodies. The other side 
of this argument is: it is generally impossible to read the function 
body, and compile it back with eval() expecting to get the same 
functional behavior because it this point we have no idea about 
closures. To accomplish that we need a way to manipulate 
closures/context: extract it from a function somehow, specify it as a 
parameter to eval()< and so on. I am not sure it is doable/practical.



More information about the Es-discuss mailing list