HighDots Forums  

Scoping issue with a function

JavaScript discussion (multi-lingual) JavaScript discussion (alt.comp.lang.javascript)


Discuss Scoping issue with a function in the JavaScript discussion (multi-lingual) forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
zburnham@gmail.com
 
Posts: n/a

Default Scoping issue with a function - 04-06-2006 , 08:00 AM






Hello all.

Please take a look at the following pseudocode:

function takeAParam(param) {

if (foo == bar) {
var baz = object.bat;
}

document.getElementById(param).innerHTML = baz;
}

Essentially what I'm trying to do here, is make a generic function that
will place specified content (from an object variable) in a specific
element (identified by 'param'.) When I try this code (with the right
specifications, etc.) I get "undefined" in that element. It appears to
be the case where baz is not visible outside the if loop. I would know
how to fix this in Java (declare the variable baz before the if loop)
but that doesn't seem to help in Javascript.

Any input would be appreciated.


Reply With Quote
  #2  
Old   
Rob Williscroft
 
Posts: n/a

Default Re: Scoping issue with a function - 04-08-2006 , 08:29 AM






wrote in news:1144328445.063117.244730 (AT) j33g2000cwa (DOT) googlegroups.com in
alt.comp.lang.javascript:

Quote:
Hello all.

Please take a look at the following pseudocode:

function takeAParam(param) {

if (foo == bar) {
var baz = object.bat;
}

document.getElementById(param).innerHTML = baz;
}

function takeParam( param )
{
if ( foo == bar )
{
document.getElementById(param).innerHTML = object.bat;
}
}

Quote:
Essentially what I'm trying to do here, is make a generic function that
will place specified content (from an object variable) in a specific
element (identified by 'param'.) When I try this code (with the right
specifications, etc.) I get "undefined" in that element. It appears to
If foo != bar what would you expect to happen ? baz would never
be assigned so is is *undefined*.

Quote:
be the case where baz is not visible outside the if loop. I would know
how to fix this in Java (declare the variable baz before the if loop)
but that doesn't seem to help in Javascript.

The initial value of a variable (without an initialiser) is *undefined*
in javascript.

IOW if you want it to be defined you have to define (initialise/assign)
it.

Rob.
--
http://www.victim-prime.dsl.pipex.com/


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.