od*********@gmail.com writes:
I have just discovered the "with" statement, which up until now I have
only known as "that which should never be used".
Closer to "use with *extreme* care", because you have no way of knowing
what properties exist on the object you are "with"'ing with.
I would like to evaluate some commands (such as function definitions
and the like) within the global context, would this accomplish the
task? Are there better ways to deal with this? (Note that I am
making dynamic execution a requirement)
function executeAsGlobal(cmd)
{
with(window) exec(cmd);
No.
What "with" does is to add its operant to the scope chain before executing
the statements.
That means that the statement "exec(cmd)" is executed with variables
being resolved against the global object first, and the scope chain
of the "executeAsGlobal" closure afterwards. That is all.
It does not change the value of the "this" operator, or of the variables
object. That means that variables created by "exec(cmd)" will end up
in the variables objec of the invocation of "executeAsGlobal", not in
the global scope.
This might be sufficient for your use, but it is not the same as
executing within the global context.
Also, the command given here as example, "exec(cmd)" is a simple function
call. Both "exec" and "cmd" are looked up with the global object first
(potentially overriding the function parameter "cmd" if the global object
contains a "cmd" property), but the execution of the function "exec" will
happen in the scope chain stored in that function's closure.
If you mean "eval" instead of "exec", then the "cmd" code is executed
in the same scope as the call, so it inherits the enhanced scope chain
and the unchanged variables object. I.e.
function foo() {
with (window) { eval("var x = 42;"); }
}
foo();
would not create "x" as a global variable.
I have used this trick myself, but one has to be aware of the limitations.
(The only way I know of to have code executed in the global scope from
inside a function scope is to use setTimeout/setInterval with a string
parameter, but you can't do that synchroneously).
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'