javascript scope

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

javascript scope

Post 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... :?
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post 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.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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.
Post Reply