On Sep 1, 9:31*pm, "optimistx" wrote:
Quote:
On further testing of this function there was a disappointment:
only variables in the global scope can be used, because eval()
works in global scope. Perhaps a modification to handle scope could
be found.
>
Also if the characters between quotes are not a variable name in global
scope then alertt behaves very badly *(perhaps adding
try ...catch would help).
>
The growing length of alertt is not important
because it is used in testing only.
As Evertjan said: eval is evil, and now it seems also inconvenient for
this function. I think it's better to pass the variables themselves as
opposed to a string which needs to be eval'ed. This is my attempt at
the function:
function alertt(a) {
var result = 'Variable name and value\n';
for (k in a) {
result += (k + ' = ' + a[k] + '\n');
}
alert(result);
return result;
}
It is meant to be called like:
var a = 'test';
var b = 123;
var c = true;
alertt({
a:a,
b:b,
c:c
});
To explain these line if they aren't immediately clear: the function
takes an object with the keys as the names of the variables and the
values as the values of the variables. So the "a:a" sets the key on
the left of the colon to "a" and the value on the right of the colon
to the value of "a".
I don't think a try...catch helps in the version I wrote because when
I've tested it the Reference Error occurs on the line that calls the
function. I think the trade off is that you could use the try...catch
in the original string/eval function but it has that problem with only
working on globals whereas I'm not sure how I'd use try...catch in the
function I wrote, but it should be able to understand any variables
that are available to the level of scope from which it is called.
Hope another take on the function provides some insight.
--
Dan Evans