Or, at the risk of offending those who so far only moderately despise
"with", and highly despise "eval",
That would be me
you could alternatively re-manifest the return object properties
into caller variables by:
for (var j in retObj) eval(j +"=retObj['"+j+"']");
This differs from using "with" in two ways:
- You only get the values of the enumerable properties of retObj.
Using "with" makes all the properties visible. That is not so much of
a difference, since the non-enumerable properties of a new object (the
ones in Object.prototype) are already visible as properties of the
global object.
- It assigns the values to local variables if they exist, but those
properties that don't have a local variable of the same name are
created as global variables. With a "with", they are all made local
variables, but will shadow preexisting local variables of the same
name.
This is actually a use for eval that I can't find a way around:
setting the value of a local variable given its name as a string.
It is also bad coding practice. Local variables should be free to
be renamed without changing the how the program works, but this
code will let a function from anywhere in the program change a local
variable by name. I recommend against it.
I would recommend returning an array and have the caller decide which
variables to assign to, or returning an object, and letting the caller
decide how to access the properties.
which might come a little closer to call by name than the use of
"with".
Maybe a little closer, but it is not call-by-name. It is
call-by-copy-restore, but I think that is the best we can get anyway.
That's in the vein of a somewhat neutral observation, as
opposed to a recommendation, however.
(By the way, I fully concur with the attempt to stamp out the evil of
[completely unnecessary use of] eval. Nonetheless, I have run into
cases where only the name of a variable is known, and in the absence
of an available reference, have taken the reasonable course and
eval'ed in order to assign/retrieve a value. If there's a good
alternative, the doh'lt is yet to discover it.)
If the variable is a local variable, then I can't see another way,
since we don't have a reference to the activation object. I highly
recommend not to throw around the names of local variables, though.
Make the global if someone outside of the scope needs to have access
to them.
/L