Csaba Gabor wrote:
for example, I'd like to call
function sample(oOptions ) {
var key1 = "key1 default";
var key2 = "key2 default";
var idx;
if (arguments.leng th>0)
for (idx in oOptions)
window.sample[idx] = oOptions[idx]; // this line wrong
alert (key1);
}
with sample({key1:"k ey1 was set"}) and have the alert be:
"key1 was set"
Subsequently, Random wrote: I'm not sure how to do exactly what you're trying here, or even if it
can be done. I'll hope someone posts a more appropriate response.
.... I can't make any better recommendations without understanding more of
your end goal.
My goal is just to understand the DOM better as it relates to functions
and their variables. The background motivation was in thinking about a
compact way to provide named arguments to javascript functions (which
is useful if you have a large universe of possible options that you
aren't expecting to change from default values). The following slight
modification does what I want (though not bulletproof - nothing ensures
that all the variables passed in will be local unless I've already
declared them inside the function with var), but it uses the much
reviled eval:
function sample(oOptions ) {
var key1 = "key1 default";
var key2 = "key2 default";
var idx;
if (arguments.leng th>0)
for (idx in oOptions)
eval(idx + " = oOptions[idx]"); // <= eval usage
alert (key1);
alert (key2);
}
sample({key1:"k ey1 was set"});
The point is that this is a small piece of portable code which could be
plunked into any function (just make sure it comes after defaults are
set). There is no need for customization of the code dealing with
oOptions on a per function basis. It's up to the caller to pass in
whatever it would like to override. Still, It would be nice if that
eval weren't there ...
Csaba Gabor from Vienna