knocte <knocte@NO-SPAM-PLEASE-gmail.com> writes:
[color=blue]
> I have always thought that the eval() function was very flexible and
> useful.[/color]
I feel the same way about flamethrowers :)
[color=blue]
> If I use it, I can define functions at runtime!![/color]
What can you do with "eval" that you can't do with one or more
function expressions?
Working with syntax at runtime is ... volatile. Just like
flamethrowers :)
[color=blue]
> However, I have found a case where eval() does not work properly.[/color]
Not according to specification or not as you would want it to work?
[color=blue]
> It works, for example, when invoking functions (alert('hello')), but
> not for defining functions.[/color]
.... but you said above that ... ? :P
[color=blue]
> The case occurs when retrieving the javascript code with
> XMLHttpRequest(). It fails on Mozilla/Firefox and IE![/color]
[color=blue]
> I will quote the code:[/color]
Actual code and platform where it fails, as well as a description of
the error later ... a good error report :) Keep it up!
Have you tried any other browser?
[color=blue]
> <script>[/color]
Use valid HTML. That way you can be sure that it's not the HTML that
causes your problems. In this case:
<script type="text/javascript">
[color=blue]
> function RequestDocument(sURL, bAsync) {
> var oXmlRequest;
>
> /* branch for native XMLHttpRequest object */[/color]
....[color=blue]
> else if (window.ActiveXObject) {
> oXmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
> oXmlRequest.open("GET", sURL, bAsync);
> oXmlRequest.send();
> }[/color]
Why not set an onreadystatechange handler to inform you when the
request is done (when asynchroneous)?
Anyway...
[color=blue]
> function LoadScriptFile(sURL){
> var oScriptFileRequest = RequestDocument(sURL,false);
> EvalScriptFile(oScriptFileRequest);
> }[/color]
.....[color=blue]
> //this works:
> eval("alert('hello');function test(){ alert('test'); };");
> test();[/color]
But does this work?
---
function LoadScriptLiteral() {
eval("alert('hello');function test(){ alert('test'); };");
}
EvalScriptLiteral();
test();
---
It doesn't work, because the content is evaluated in the same scope as
the call to eval. That means that the declaration of test() happens
inside the function LoadScriptLiteral, and can't be seen outside of
it.
You have the same problem, because you call "eval" inside
LoadScriptFile.
One soultion would be to let the script declare its variables as
global variables:
var global = (function(){return this;})();
global.test2 = function() { alert("test2"); }
Not as pretty, but guaranteed to work.
I can't find a better way of doing it right now, but I'll keep
pondering :)
Good luck!
/L
--
Lasse Reichstein Nielsen -
lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'