Page 1 of 1

javascript scope

Posted: Thu Dec 07, 2006 5:14 pm
by Luke
For some reason javascript's scoping confuses me... I have read that this should work in my book as well as google maps documentation, but it doesn't...

Code: Select all

var map;
function loadGoogleMap(id)
{
    map = new GMap2(document.getElementById(id));
}
alert(map); // alerts "undefined" shouldn't it be Object [Object]?
In my book it tells me that if you don't specify var map = bla bla, it assumes global scope and then should assign the GMap2 object to the global map variable, but it doesn't... am I reading wrong? Am I perhaps retarded? I've never been able to figure this out... :?

Posted: Thu Dec 07, 2006 5:41 pm
by Luke
nevermind... I get it...

Code: Select all

var map;
function doSomething()
{
    map = new Object;
}
alert(map); // This happens before doSomething() is even called. 
I always post and then realize the answer to my own post. I think I need to stop doing that.

Posted: Fri Dec 08, 2006 4:21 am
by Maugrim_The_Reaper
Like any language, you should limit the scope of variables.

If possible, do not declare map at all outside a function/object scope. Rather let the function return the value to where it is actually being used. This isn't any different to PHP really.

Posted: Fri Dec 08, 2006 10:55 am
by Luke
Well at first I had built a series of classes to work with the maps, but I was having way to hard of a time with the "this" keyword (keyword... is that the right word?) always changing within the function. I could never figure out what "this" referred to... javascript's object model is really strange (coming from purely php background) to me. I just could not get the hang of it and so due to deadlines being over a month ago, I scrapped the whole object-oriented approach and decided to go with the noob approach. Believe me... I hate building it like this, but I just do not have enough time to learn how to do it the right way. I bought a gigantic Javascript book (JavaScript: The Definitive Guid, by David Flanagan), but I just don't have the time right now to really learn it right.