|
Posted by Michael Winter on 07/08/05 16:17
On 08/07/2005 12:05, ^reaper^ wrote:
[snip]
> Or, for example, say you want to reference a document object that
> contains a variable component, you can do something like this:
>
> eval('document.all.'+name+'.style');
Even then, it's not necessary:
document.all[name].style
The eval function is best left for /arbitrary/ strings that need to be
evaluated as code. However, it is very rare that one will ever have such
a need.
The only use I've found so far is for emulating the
Function.prototype.call or apply methods in (mainly) earlier IE
versions. Unlike the dynamic construction of property names, there is no
other way of building an argument list at run-time without the use of
the apply method.
var global = this;
if('function' != typeof Function.prototype.apply) {
Function.prototype.apply = function(o, a) {
var x = [],
p = ' $apply',
r, u;
if(null == o) {o = global;}
while('undefined' != typeof o[p]) {p += p;}
o[p] = this;
if(a && (Array == a.constructor) && a.length) {
for(var i = 0, n = a.length; i < n; ++i) {x[i] = i;}
r = eval('o[p](a[' + x.join('],a[') + ']);');
} else {
r = o[p]();
}
o[p] = u;
return r;
};
}
Still, even that has a slight problem. Though IE will set the this
operator value correctly for a null or undefined first argument, this
value will not compare properly to the global object.
All that said, given the fact that one usually knows how many arguments
will be needed in a call to one of these methods, this form of generic
emulation is rarely needed.
I have seen other interesting uses for the eval function, but even they
weren't really necessary.
Mike
--
Michael Winter
Prefix subject with [News] before replying by e-mail.
[Back to original message]
|