Click to See Complete Forum and Search --> : Declaring functions in JavaScript??


hasenmaus
01-26-2003, 08:37 AM
I recently ran into a problem in both Netscape 7.01 and Mozilla 1.2.1. When trying to call a JS function from within a function, the JS Debugger indicates that the function has not been declared.

Do you now have to declare functions as in C before using them? See the JS code snippet below. In Netscape 7.01, foobar() never gets called. Note: I placed periods "." in the tags below so that browsers would not think the code was HTML or JavaScript.

Would appreciate if anyone has encountered a similar problem, and if there is a work around. It seems to be a bug in the Netscape/Mozilla code.


<.html>
<.head>
<.script language = "JavaScript">
function foo(){
document.write("Hello, how are you?");
foobar();
}

function foobar(){
document.write("Just fine, thanks!");
}
<./script>
<./head>
<.body onLoad="foo()">
<./body>
<./html>

khalidali63
01-26-2003, 11:03 AM
Your problem is "scope" problem.once you use document.write there is nothing else after that line of code that executes.

your only chioce will be the pass the first message as string to foobar() function and use document.write in the foobar prefixing the message string from the first method.

cheers

Khalid


<script type="text/javascript">
function foo(){
var str = "Hello, how are you?";
foobar(str);
}

function foobar(str){
document.write(str+"<br>Just fine, thanks!");
}

</script>
</head>

<body onLoad="foo()">

hasenmaus
01-26-2003, 01:30 PM
Thanks Dave and Khalid,

I understand your suggestions and they work just fine. I guess what I don't understand is that my code fragment works just fine in IE 5.0??

Regards,

Tim

Webskater
01-26-2003, 05:05 PM
Originally posted by khalidali63
Your problem is "scope" problem.once you use document.write there is nothing else after that line of code that executes.


Can anyone explain why, as stated above, using document.write seems to stop anything after that line happening - yet, I see other people using line after line of 'document.write' to build complete pages e.g
document.write('table');
document.write('<tr>');
document.write('<td>'); etd.

I know I'm missing something basic here.

hasenmaus
01-26-2003, 06:12 PM
Dave,

IE seems to work as I would expect it a "compiled" program to work. i.e., when a function is called the address of the last unexecuted line in the calling function is placed on the stack. Then when the called function returns it knows where to resume execution of function.
Netscape appears to be throwing a null pointer exception. That is, it doesn't appear to know the address of the the function that is being called.

Tim